Peter Matisko
Peter Matisko

Reputation: 2253

Webpack, Scss - add cdn server path before compilation

How do I add a cdn path variable into the styles.scss before compilation? I have a webpack 4 configuration that works fine for JS. The JS/CSS files are loaded correctly from the desired cdn url.

What I want to achieve is, that the project running on localhost will use a different cdn url for images/icons/fonts than the same web running on production.

My webpack config has these lines for setting the cdn domain:

if (process.env.NODE_ENV === 'production') {
    webUrl = 'https://cdn.project.com/';
}
else if (process.env.NODE_ENV === 'development') {
    webUrl = 'http://localcdn.localhost/';
}

This code works well for JS/CSS files, but CSS always loads backgrounds/fonts using a relative path, which of course is the main domain and not the cdn.

Maybe just open the styles.scss and update the file manually before webpack compilation? Isn't there a better way?

Upvotes: 1

Views: 1839

Answers (2)

Peter Matisko
Peter Matisko

Reputation: 2253

For webpack 5, the config changed a little:

  {
      loader: 'sass-loader',
      options : {
                   additionalData : "$cdnFolder: '" + cdnUrl + "';"
                }
   }                      

Upvotes: 0

Peter Matisko
Peter Matisko

Reputation: 2253

After hours of trial and error I found this solution for webpack 4. It may help someone trying to solve the same issue.

        {
            test: /\.(sa|sc|c)ss$/,
            use: [
                MiniCssExtractPlugin.loader,
                {
                    loader: 'css-loader',
                    options : {
                        url : false,
                        sourceMap: devMode
                    }
                },
                {
                    loader: 'sass-loader',
                    options : {
                        processCssUrls : false,
                        sourceMap: devMode,

                        data : "$cdnFolder: 'http://cdn.myweb.net/';"
                    }
                }
            ],
        },

This is a part of webpack.config.js, in the section:

module : {
  rules : {

This configuration makes the scss variable $cdnFolder available in every scss file. CDN link can be changed based on the current mode dev/prod/stage.

Upvotes: 4

Related Questions