Reputation: 708
I'm trying to inject NODE_ENV into a sass file, so I can have different output for dev/prod env, and have a sass function that has a condition like that 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 a data parameter to the loader, but nothing that I tried worked. will appreciate any help!
Upvotes: 8
Views: 4665
Reputation: 23845
prependData
option for sass-loader
{
loader: 'sass-loader',
options: {
prependData: '$env: ' + process.env.NODE_ENV + ';',
}
}
prependData
also accepts a function
which receives the loaderContext
with which you can make it more dynamic. Once you have implemented this; you can :
@if ($env == 'prod') {}
More information here : https://webpack.js.org/loaders/sass-loader/#prependdata
Good Luck...
Upvotes: 3
Reputation: 1456
this is the code directly from sass-loader repo.
webpack.config.js
...
sassLoader: {
data: "$env: " + process.env.NODE_ENV + ";"
}
...
Upvotes: 7
Reputation: 2652
Took a look at the sass-loader
source and it doesn't seem to support any options that would allow you to insert a variable -- so it won't be possible this way.
I don't think you'll be able to 'insert' an env/build-time variable into your Sass like this, but you could get the same behavior by creating multiple Sass files and requiring the one you want (from your js source) based on a condition. Note that webpack has limited ability to parse the logic in your code, however -- if you want to require
something within a conditional, the conditional has to check a boolean value for it to work. So if you do if (NODE_ENV === 'production') {...} else {...}
webpack will process all the requires in all those conditions. If you did something like if (IS_PROD_ENV) {...} else {...}
, where the conditional value is a boolean, webpack will follow the conditional logic and only process the correct require
. The UglifyJS
plugin will remove the unneeded conditional branches for you.
Upvotes: 0