Can I enter the NODE_ENV parameter in the sass file using the Webpack & sass loader?

I am trying to enter NODE_ENV in a sass file, so I can have a different output for dev / prod env and there is a sass function that has the same condition inside it: @if (NODE_ENV == 'prod') {}

my webpack.config looks like this:

module: {
    loaders: [{
        test: /\.scss$/,
        loader: "style-loader!raw-loader!sass-loader?includePaths[]=" + path.resolve(__dirname, "./node_modules/compass-mixins/lib")
    }]
}

I tried passing the data parameter to the loader, but nothing I tried worked. appreciate any help!

+5
source share
3 answers

this is code directly from the sass-loader repository.

webpack.config.js

... sassLoader: { data: "$env: " + process.env.NODE_ENV + ";" } ...

+5
source

sass-loader, , , , , .

, "" env/build-time Sass, , , Sass , ( js) . , - , - require - , . , if (NODE_ENV === 'production') {...} else {...}, - . - if (IS_PROD_ENV) {...} else {...}, , webpack require. UglifyJS .

0

You can try the option prependDataforsass-loader

{
  loader: 'sass-loader',
  options: {
    prependData: '$env: ' + process.env.NODE_ENV + ';',
  }
}

prependDataalso accepts function, which receives loaderContext, with which you can make it more dynamic. Once you have implemented it; You can:

@if ($env == 'prod') {}

More info here: https://webpack.js.org/loaders/sass-loader/#prependdata

Good luck ...

0
source

All Articles