Webpack中的规则(Rules)和加载器(Loaders)有什么区别?

87

在一些Webpack示例中,你会看到对一个"rules"数组的引用:

module.exports = {
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          //resolve-url-loader may be chained before sass-loader if necessary
          use: ['css-loader', 'sass-loader']
        })
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin('style.css')
    //if you want to pass in options, you can do so:
    //new ExtractTextPlugin({
    //  filename: 'style.css'
    //})
  ]
}

(https://github.com/webpack-contrib/extract-text-webpack-plugin)

另外,在一个loaders数组中:

var ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
    module: {
        loaders: [
            {
                test: /\.css$/,
                loader: ExtractTextPlugin.extract({
                    loader: "css-loader"
                })
            },
            { test: /\.png$/, loader: "file-loader" }
        ]
    },
    plugins: [
        new ExtractTextPlugin({
            filename: "style.css",
            allChunks: true
        })
    ]
};

(https://github.com/webpack/webpack/tree/master/examples/css-bundle)

有何区别?应该使用哪个?


7
模块加载器现在被称为模块规则。在Webpack 1中,你使用"module.loaders"配置选项来定义如何处理各种类型的模块。在Webpack 2及以上版本中,你需要使用"module.rules"配置选项来完成相同的任务。这个新名称更准确地反映了规则系统的工作方式,因为它不仅限于加载器,也可以包括其他类型的规则。 - Ivan
1
现在位于 https://webpack.js.org/migrate/3/#module-loaders-is-now-module-rules。 - Jayson Cheng
1个回答

97

Loaders在Webpack 1中使用,
Rules在Webpack 2+中使用。

根据官方Webpack网站的迁移文档

module.loaders现在改为module.rules

旧的loader配置已被更强大的rules系统所取代,该系统允许对loader进行配置等。由于兼容性原因,旧的module.loaders语法仍然有效,旧名称也会被解析。新的命名规则更易于理解,是升级配置以使用module.rules的好理由。

Delta示例

  module: {
-   loaders: [
+   rules: [
      {
        test: /\.css$/,
-       loaders: [
-         "style-loader",
-         "css-loader?modules=true"
+       use: [
+         {
+           loader: "style-loader"
+         },
+         {
+           loader: "css-loader",
+           options: {
+             modules: true
+           }
+         }
        ]
      },
      {
        test: /\.jsx$/,
        loader: "babel-loader", // Do not use "use" here
        options: {
          // ...
        }
      }
    ]
  }

有官方参考资料吗? - user753676
1
https://webpack.js.org/guides/migrating/#module-loaders-is-now-module-rules - user753676
3
当我添加 Babel 集成时,我使用了一个示例中的加载器部分,但没有注意到这一点,而我的项目使用规则(rules),这些规则在加载器部分之后执行。我花了几个小时研究为什么 babel 不起作用!因为规则(rules)静默地覆盖了加载器部分 :( - Daniil Iaitskov

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