john_ryan
john_ryan

Reputation: 1787

Configuring css-loader with publicPath

I have a .scss file with a class:

.my-class {
  background-image: url("/images/image.svg")
}

When building with webpack i'm using a publicPath in my configuration. Let's say my public path is XYZ

i'd like to find a way to find the generated css to look like:

.my-class {
  background-image: url("/XYZ/images/image.svg")
}

All the other assets generated seem to honor that publicPath variable so it's unclear what i've misconfigured. My config looks like this:

 {
        test: /^((?!\.global).)*\.scss$/,
        use: [
          { loader: require.resolve('style-loader') },
          {
            loader: require.resolve('css-loader'),
            options: {
              modules: true,
              importLoaders: 1,
              camelCase: true,
              localIdentName: '[name]__[local]__[hash:base64:5]'
            }
          },
          {
            loader: require.resolve('sass-loader')
          }
        ]
      },

Upvotes: 4

Views: 4125

Answers (2)

Brett East
Brett East

Reputation: 4322

So the easiest thing I've seen to fix this is to update your css-loader options to url: false.

This previously worked out of the box for me with [email protected] but looks like you now need this option.

My webpack now looks like this:

...
  module: {
    rules: [
      ...
      {
        test: /\.scss$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'style-loader',
          },
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
              modules: {
                localIdentName: '[name]__[local]__[hash:base64:5]',
              },
              url: false, //<------------ this guy helped
            },
          },
          {
            loader: 'sass-loader',
          },
        ],
      },
      ...
    ],
  },
...

Upvotes: 1

divine
divine

Reputation: 4912

You could inject a scss variable that holds publicPath value using webpack.

Pass the scss variable with your value under the options in sass-loader

var publicpath = "/static/images";
module.exports = {
  ...
  module: {
    rules: [{
            test: /\.scss$/,
            use: [{
                loader: "style-loader"
            }, {
                loader: "css-loader"
            }, {
                loader: "sass-loader",
                options :{
                    data:"$publicpath : "+publicpath+";$red : red;$blue:blue;"
                }
            }]
        }]
    }
};

in main.scss or any .scss you can access the value

.h1{
    color: $red;
}
.h2{
    color: $blue;
}
.img{
    background-image: url($publicpath+"/pic.jpg");
    width: 200px;
    height: 200px;
    background-size: 100%;
    background-repeat: no-repeat;
}

Upvotes: 0

Related Questions