Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

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

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
    }
  };
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...