How to add a query to a webpack loader with multiple loaders?

Chet picture Chet · Oct 14, 2015 · Viewed 31.6k times · Source

I have this Babel loader that's working

{ test: /\.jsx?$/, loader: 'babel', query: babelSettings, exclude: /node_modules/ },

But now I want a CoffeeScript loader but I want to pipe it through Babel to get the the fancy HMR stuff

{ test: /\.coffee$/, loader: 'babel!coffee', query: babelSettings, exclude: /node_modules/ },

This doesn't work though, and results in the following error.

Error: Cannot define 'query' and multiple loaders in loaders list

Any idea how to define the query just for the Babel part of the loader chain? The query is a complicated object and I don't think I can encode it.

var babelSettings = { stage: 0 };

if (process.env.NODE_ENV !== 'production') {
  babelSettings.plugins = ['react-transform'];
  babelSettings.extra = {
    'react-transform': {
      transforms: [{
        transform: 'react-transform-hmr',
        imports: ['react'],
        locals: ['module']
      }, {
        transform: 'react-transform-catch-errors',
        imports: ['react', 'redbox-react']
      }]
      // redbox-react is breaking the line numbers :-(
      // you might want to disable it
    }
  };
}

Answer

Alexander O'Mara picture Alexander O'Mara · Oct 14, 2015

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"}).