5
votes

In my vue(2.0)+ webpack project, I config vue-html-loader, but in my .vue files img tag cannot load static src images. Below is my webpack config:

module: {
    loaders: [
        ...
        {
            test: /\.html$/,
            exclude: /node_modules/,
            loaders: ['html', 'html-minify']
        }
        , {
            test: /\.vue$/,
            loader: 'vue'
        }
        ...
    ]
},
vue: {
    ...
    html: {
        root: path.resolve(__dirname, './source/static'),
        attrs: ['img:src', 'img:srcset']
    },
    loaders: {
        css: ExtractTextPlugin.extract("css"),
        sass: ExtractTextPlugin.extract("css!sass")
    }
},
resolve: {
    root: [
        path.resolve('./source')
    ],
    extensions: ['', '.js', '.json', '.scss', '.html', '.css', '.vue'],
    alias: {
        'vue': 'vue/dist/vue.js'
    }
},

Below is my .vue file:

<img src="/web/img/[email protected]" srcset="/web/img/[email protected]" />

My browser always come out 404 error. Did somebody get the same problem?

2
I think you need the url-loader for static images. I highly recommend the webpack template used by vue-cli. See github.com/vuejs-templates/webpack/blob/master/template/build/…Phil
@Phi Ihave added the url-loader, bug it doesn't work.Yuga

2 Answers

0
votes

I have following in my webpack config, which works for me:

  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue',
        options: vueConfig
      },
      {
        test: /\.js$/,
        loader: 'babel',
        exclude: /node_modules/
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: 'url',
        options: {
          limit: 10000,
          name: '[name].[ext]?[hash]'
        }
      }
    ]
  }

I have images in the src/assets folder which I can access and display without any specific setting.

0
votes

I'd add an alias for your static img directory within your webpack aliases, i.e.

resolve: {
  ...
  alias: {
    'vue': 'vue/dist/vue.js',
    'img': path.resolve(__dirname, '../web/img') // or wherever it is located relative to this file
  }
}

now you can reference static images via ~img, i.e.

<img src="~img/[email protected]" srcset="~img/[email protected]" />

To ensure you can parse the above within your html you need to add the vue-html loader to your webpack config:

module: {
  loaders: [
    ...
    {
        test: /\.html$/,
        loaders: 'vue-html'
    }

I would just replace your current html loader with the above.

However all this aside - due to the complexity of scaffolding a solid webpack vue application I'd strongely recommend you install the vue-cli: https://github.com/vuejs/vue-cli

Then you can simply roll out a tested and functioning webpack environment:

https://github.com/vuejs-templates/webpack

Simply copy your application into it. You'll likely have to do a bit of refactoring but the time saving on the set up is absolutely worth it.