tawreon
tawreon

Reputation: 184

Webpack doesn't create right paths for images in production css file

To add images into the project i'm using content: url() css property inside sass file and specify relative path to src folder e.g. content: url('/images/right-arrow.svg');.

The problem is that in production build i need to get rid of the first slash to have such path ('images/right-arrow.svg') inside of a bundled css file.

The only way i could get desired behaviour is to use url: false option for css-loader, and writing path without slash in sass file: content: url('/images/right-arrow.svg'), but such option don't add necessary file from node_modules e.g. fonts and images.

Webpack Config:

return {
entry: ['babel-polyfill', './src/app.js'],
output: {
  path: path.join(__dirname, 'public/'),
  filename: '[name].[hash].js',
},
mode: isProduction || 'development',
module: {
  rules: [
    {
      loader: 'babel-loader',
      test: /\.js$/,
      exclude: /node_modules/
    },

    {
      test: /\.s?css$/,
      use: [
        isProduction ? MiniCssExtractPlugin.loader : 'style-loader',
        {
          loader: 'css-loader',
          options: {
            url: true
          }
        },
        'sass-loader'
      ]
    },

    {
      test: /\.(svg|gif|png)$/,
      use: {
        loader: 'file-loader',
        options: {
          name: '[name].[ext]',
          outputPath: 'images'
        }

      }
    },

    {
      test: /\.(otf|woff2|ttf|eot|woff)$/,
      use: {
        loader: 'file-loader',
        options: {
          name: '[name].[ext]',
          outputPath: 'fonts/'
        }
      }
    }

  ]
}

What am i missing in webpack config to achieve paths to work correcty?

Upvotes: 2

Views: 2442

Answers (2)

tawreon
tawreon

Reputation: 184

Ok, I've solved the issue. I was using resolve-url-loader with no results, before @Ujin suggested to use it. After his comment I've clarified what resolve-url-loader does and cofigured it propertly to solve my issue. The main problem is that I've missed to read important paragraph of resolve-url-loader docs, which says:

source-maps required for loaders preceding resolve-url-loader (regardless of devtool).

Also I didn't use root option of resolve-url-loader plugin. So, webpack config for .scss files looks like this:

      test: /\.s?css$/,
      use: [
        isProduction ? MiniCssExtractPlugin.loader : 'style-loader',
        'css-loader',
        {
          loader: 'resolve-url-loader',
          options: {
            root: path.join(__dirname, 'src')
          }
        },
        {
          loader: 'sass-loader',
          options: {
            sourceMap: true,
            sourceMapContents: false
          }
        }
      ]
    }

Upvotes: 6

UjinT34
UjinT34

Reputation: 4987

Check the documentation about problems with url(...). It suggests using resolve-url-loader.

Also you can try to use copy-webpack-plugin

Upvotes: 0

Related Questions