如何向具有多个加载器的 webpack 加载器添加查询? [英] How to add a query to a webpack loader with multiple loaders?

查看:24
本文介绍了如何向具有多个加载器的 webpack 加载器添加查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个正在运行的 Babel 加载器

I have this Babel loader that's working

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

但现在我想要一个 CoffeeScript 加载器,但我想通过 Babel 将其通过管道传输以获取花哨的 HMR 内容

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

知道如何为加载器链的 Babel 部分定义查询吗?查询是一个复杂的对象,我认为我无法对其进行编码.

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
    }
  };
}

推荐答案

更新: 使用非遗留版本的 Webpack 你可以在 Webpack 配置中定义一个加载器数组.

Update: With non-legacy versions of Webpack you can define an array of loaders in the Webpack configuration.

如果您需要使用旧版本的 Webpack 或内联添加选项,原始答案如下.

If you need to use an older versions of Webpack or add the options inline, the original answer is below.

这样做的方法是在加载器字符串本身中设置查询参数,因为 query 对象键仅适用于一个加载器.

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.

假设您的设置对象可以序列化为 JSON,如您的示例所示,您可以轻松地将设置对象作为 JSON 查询传递.那么只有 Babel 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:

使用加载器:查询参数

大多数加载器都接受普通查询格式 (?key=value&key2=value2) 和 JSON 对象 (?{"key":"value","key2") 的参数:"value2"}).

Most loaders accept parameters in the normal query format (?key=value&key2=value2) and as JSON object (?{"key":"value","key2":"value2"}).

这篇关于如何向具有多个加载器的 webpack 加载器添加查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆