如何在具有多个加载器的webpack加载器中添加查询?

55

我有一个正常工作的Babel加载器。

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

但现在我想要一个 CoffeeScript 加载器,但我希望通过 Babel 管道传递它以获得花哨的 HMR 功能。

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

然而,这样做行不通,会导致以下错误。

错误:无法同时在加载器列表中定义“query”和多个加载器

有什么办法只为loader链中的Babel部分定义查询吗? 查询是一个复杂的对象,我不认为我能编码它。

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
    }
  };
}
4个回答

30

更新:在非遗留版本的Webpack中,您可以在Webpack配置中定义一系列加载器

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


实现此操作的方法是在加载器字符串本身中设置查询参数,因为query对象键仅适用于一个加载器。

假设您的设置对象可以序列化为JSON,如您的示例所示,您可以将设置对象作为JSON查询轻松传递。然后只有Babel加载器会获取这些设置。

{ test: /\.coffee$/, loader: 'babel?'+JSON.stringify(babelSettings)+'!coffee', exclude: /node_modules/ }

这个功能的使用方法在这里有部分文档:

使用加载器:查询参数

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


14

Webpack的创建者Sokra在这里提出了他自己的建议,但是您可能更适合使用webpack-combine-loaders助手,因为它的风格更类似于使用查询对象定义单个loader。

使用webpack-combine-loaders,您可以这样定义多个加载程序:

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',
      ],
    },
  },
]);

13

webpack 2 和 3 中,这可以更加清晰地配置。

加载器可以通过一个装载器对象的数组传递。每个加载器对象可以指定一个 options 对象,其作用类似于 webpack 1 的特定加载器的 query

例如,在 webpack 2 和 3 中,同时使用 react-hot-loaderbabel-loader,并为 babel-loader 配置一些选项。

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'
        ]
      }
    }]
  }] 
}

为了对比,这里展示了相同配置在 webpack 1 中使用查询字符串的方法。

module: {
  loaders: [{
    test: /\.js$/,
    exclude: /node_modules/,
    loaders: [
      'react-hot',
      'babel-loader?' +
        'babelrc=false,' +
        'presets[]=es2015,' +
        'presets[]=stage-0,' +
        'presets[]=react'
      ]
  }] 
}

注意到整个链条中所有属性名称的更改。

另外,请注意我在配置中将es2015预设更改为es2015-native-modules预设。这与options的规范无关,仅仅是因为包含ES6模块允许您使用v2引入的树摇晃特性。它可以不动,但如果没有指出显然的升级,答案会感觉不完整 :-)


3

test属性只是正则表达式,因此您可以同时检查jsx和coffee: test: /\.(jsx|coffee)$/

Sass/SCSS则稍微简单一些: test: /\.s[ac]ss$/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接