sassrelative-pathsass-loaderwebpack-3extracttextwebpackplugin

WebPack + SASS : How to generate relative image path?


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 :

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


Solution

  • 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
              }
            }]
          }