Search code examples
webpackvue.jswebpack-2webpack-file-loader

Reference to static assets with vue + webpack in electron app


I am new to vuejs + webpack + electron and I am starting a new project with these tools.

I have hard time retrieving the path to my asset in my tag.

My project structure is the following:

/my-project
  /app
    /components
      componentA.vue
      ...
    App.vue
    main.js
  /dist
  /assets
    logo.png
  package.json
  webpack.config.js
  ...

My webpack.config.js looks like:

module.exports = {
  // This is the "main" file which should include all other modules
  entry: './app/main.js',
  // Where should the compiled file go?
  output: {
    // To the `dist` folder
    path: './dist',
    // With the filename `build.js` so it's dist/build.js
    filename: 'build.js'
  },
  module: {
    loaders: [
      {
        test: /\.vue$/,
        loader: 'vue-loader'
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        query: {
          presets: ['es2015']
        },
        exclude: /node_modules/
      },
      {
        test: /\.(jpeg|png|gif|svg)$/,
        loader: "file-loader?name=[name].[ext]"
      }
    ]
  },
  resolve: {
    alias: {
      'vue$': 'vue/dist/vue.common.js',
    }
  }
}

In the file componentA.vue I am trying to do the following:

<template>
    <div>
        <img class="ui small image" src="../../assets/logo.png">
    </div>
</template>

<script>
   ...
</script>

But I have the following error

Failed to load resource: net::ERR_FILE_NOT_FOUND file:///logo.png

The browser tried to load file:///logo.png (which is wrong because it's not the full path of my asset, it misses the whole path to my-project directory) so I tried to put my asset in the output /dist folder with no result (but I am not sure I did it correctly).

Can you help me in resolving this issue ? Thanks a lot !


Solution

  • In order for Webpack to return the correct path you need to make the following change:

    <template>
        <div>
            <img class="ui small image" :src="imageSource">
        </div>
    </template>
    
    <script>
        export default {
            data(){
                return {
                    imageSource: require('../../assets/logo.png')
                }
            }
    </script>
    

    Reference: https://github.com/vuejs-templates/webpack/issues/126