Webpack not finding path of SVG CSS backgrounds

2019-08-13 23:41发布

The PNGs files works fine:

.marker {
  background: url(../assets/marker.png)

But when I change them to an SVG background:

.marker {
  background: url(../assets/marker.svg)

I get this: error on line 1 at column 1: Document is empty. In other words, Webpack can't find the path of the SVG file, generating something like this: data:image/svg+xml;base64,bW9kdWxlLmV4cG9ydHMgPSBfX3dlYnBhY2tfcHVibGljX3BhdGhfXyArICIyOWE3OGMyODg0ZWQyNjFhYTFjOWM1MjYxY2I1MTViZi5zdmciOw==

It does work when I use an absolute path:

.marker {
  background: url(http://istaging.co/api/marker.svg)

Why is this?

Note: this is now my Webpack file looks like:

var path = require('path')

module.exports = {
  entry: {
    app: './src/main.js'
  },
  output: {
    path: path.resolve(__dirname, '../dist/static'),
    publicPath: '/static/',
    filename: '[name].js'
  },
  resolve: {
    extensions: ['', '.js', '.vue', 'styl'],
    alias: {
      'src': path.resolve(__dirname, '../src')
    }
  },
  resolveLoader: {
    root: path.join(__dirname, 'node_modules')
  },
  module: {
    preLoaders: [
      {
        test: /\.vue$/,
        loader: 'eslint',
        exclude: /node_modules/
      },
      {
        test: /\.js$/,
        loader: 'eslint',
        exclude: /node_modules/
      }
    ],
    loaders: [
      {
        test: /\.vue$/,
        loader: 'vue'
      },
      {
        test: /\.js$/,
        loader: 'babel',
        exclude: /node_modules/
      },
      {
        test: /\.json$/,
        loader: 'json'
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: 'url',
        query: {
          limit: 10000,
          name: '[name].[ext]?[hash:7]'
        }
      },
      {
        test: /\.css$/,
        loader: 'style-loader!css-loader'
      },
      {
        test: /\.styl$/, loader: 'style-loader!css-loader!stylus-loader'
      },
      {
        test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'url-loader?limit=10000&minetype=application/font-woff'
      },
      {
        test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: 'file-loader'
      }
    ]
  },
  eslint: {
    formatter: require('eslint-friendly-formatter')
  }
}

(Do I have to change something here to make SVG files work in CSS backgrounds?)

1条回答
家丑人穷心不美
2楼-- · 2019-08-14 00:31

I would suggest using inline-svg-loader instead of file-loader for svg files.

查看更多
登录 后发表回答