WebPack + SASS : How to generate relative image path?

4.3k views Asked by At

I am trying to set up a web application behind an Apache vhost which acts as proxy (proxyPass) in order to add a contextPath. Only the vhost has to know this contextPath of course.

Everything is ok, except the background-images which are not loaded. The reason is simple :

SASS image URLs are absolute and don't contain the contextPath.

If the generated URLs in the final CSS were relative, images should be loaded correctly.

How to use SASS/Webpack in order to generate relative path then ?


Notes:

Whatever I use in SASS file, absolute or relative path, the final output is always absolute. I currently use :

  • Webpack 3
  • node-sass 4.5.3
  • sass-loader 6.0.6
  • extract-text-webpack-plugin 3.0.0

I don't use any file-loader (I tryed too but change nothing) and just copy all images in the dist directory.

1

There are 1 answers

0
user2668735 On BEST ANSWER

The solution was to set the url option to false in the css-loader (see css-loader documentation). Moreover, as soon as we use relative paths in SASS sources, we need a file-loader too, with emitFile to false if we use CopyWebpackPlugin who already in charge to copy those files in dist directory.

      {
        test: /\.(css|sass|scss)$/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: [{
            loader: 'css-loader',
            options: { url: false }
          }, {
            loader: 'sass-loader'
          }]
        })
      }, {
        test: /\.(png|svg)$/,
        exclude: /node_modules/,
        use: [{
          loader: 'file-loader?name=img/[name].[ext]',
          options: {
            emitFile: false
          }
        }]
      }