Webpack 中的规则与加载器 - 有什么区别? [英] Rules vs Loaders in Webpack - What's the Difference?

查看:26
本文介绍了Webpack 中的规则与加载器 - 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一些 Webpack 示例中,您会看到对规则"数组的引用:

In some Webpack examples, you see reference to a "rules" array:

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)

还有一个加载器数组:

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)

有什么区别?应该使用哪个?

What is the difference? Which should be used?

推荐答案

Loaders 用于 Webpack 1
Rules 在 Webpack 2+ 中使用

Loaders are used in Webpack 1
Rules are used in Webpack 2+

module.loaders 现在是 module.rules

module.loaders is now module.rules

旧的加载器配置被一个更强大的规则系统所取代,它允许配置加载器等等.出于兼容性原因,旧的 module.loaders 语法仍然有效并且旧名称被解析.新的命名约定更容易理解,并且是将配置升级为使用 module.rules 的一个很好的理由.

The old loader configuration was superseded by a more powerful rules system, which allows configuration of loaders and more. For compatibility reasons, the old module.loaders syntax is still valid and the old names are parsed. The new naming conventions are easier to understand and are a good reason to upgrade the configuration to using module.rules.

增量示例

  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: {
          // ...
        }
      }
    ]
  }

这篇关于Webpack 中的规则与加载器 - 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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