How to add a query to a webpack loader with multiple loaders?
Solution 1:
Update: With non-legacy versions of Webpack you can define an array of loaders in the Webpack configuration.
If you need to use an older versions of Webpack or add the options inline, the original answer is below.
The way to do this is to set the query parameters in the loader string itself, as the query
object key will only work for one loader.
Assuming your settings object can be serialized to JSON, as your example indicates, you could easily pass your settings object as a JSON query. Then only the Babel loader will get the settings.
{ test: /\.coffee$/, loader: 'babel?'+JSON.stringify(babelSettings)+'!coffee', exclude: /node_modules/ }
The feature for doing this is somewhat documented here:
Using Loaders: Query parameters
Most loaders accept parameters in the normal query format (
?key=value&key2=value2
) and as JSON object (?{"key":"value","key2":"value2"}
).
Solution 2:
Sokra, the creator of Webpack, gives his own take on how to do this here, but you'll probably be better served with the webpack-combine-loaders helper that's more similar in style to defining a single loader with the query object.
With webpack-combine-loaders
, you can define multiple loaders as such:
combineLoaders([
{
loader: 'css-loader',
query: {
modules: true,
sourceMap: true,
localIdentName: '[name]__[local]--[hash:base64:5]',
},
},
{
loader: 'sass-loader',
query: {
sourceMap: true,
includePaths: [
'app/assets/stylesheets',
'app/assets/stylesheets/legacy',
],
},
},
]);
Solution 3:
In webpack 2 & 3 this can be configured much more cleanly.
Loaders can be passed in an array of loader objects. Each loader object can specify an options
object that acts like the webpack 1 query
for that particular loader.
For example, using both react-hot-loader
and babel-loader
, with babel-loader
configured with some options, in webpack 2 & 3
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: [{
loader: 'react-hot-loader'
}, {
loader: 'babel-loader',
options: {
babelrc: false,
presets: [
'es2015-native-modules',
'stage-0',
'react'
]
}
}]
}]
}
For comparison, here is the same configuration in webpack 1, using the query string method.
module: {
loaders: [{
test: /\.js$/,
exclude: /node_modules/,
loaders: [
'react-hot',
'babel-loader?' +
'babelrc=false,' +
'presets[]=es2015,' +
'presets[]=stage-0,' +
'presets[]=react'
]
}]
}
Notice the changed property names all down the chain.
Also, note that I changed the es2015
preset to es2015-native-modules
preset in the babel-loader
configuration. This has nothing to do with the specification of options
, it's just that including es6 modules allows you to use the tree-shaking feature introduced in v2. It could be left alone and it would still work, but the answer would feel incomplete without that obvious upgrade being pointed out :-)