简体   繁体   English

为什么要在webpack conf文件中添加babel-loader?

[英]Why adding babel-loader in webpack conf file?

I am new to webpack and have seen some examples as following: 我是webpack的新手,并且看到了以下示例:

module: {
    rules: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      // ....

Why is this necessary since webpack auto transpiles es6 to es5? 由于webpack自动将es6转换为es5,为什么这是必需的?


Edit: Ok, it DOES NOT transpile automatically unless instructed to do so. 编辑:好的,除非有指示,否则它不会自动进行转换。

Why is this necessary since webpack auto transpiles es6 to es5? 由于webpack自动将es6转换为es5,为什么这是必需的?

Webpack does not auto-transpile ES6 to ES5. Webpack不会将ES6自动转换为ES5。 It is simply a build tool. 它只是一个构建工具。 It does nothing but execute the plugins & loaders you tell it to. 除了执行您告诉它的插件和加载程序外,它什么都不做。

But the es6 code I wrote get transpiled to es5 even without this "babel" rule 但是即使没有此“ babel”规则,我编写的es6代码也被转换为es5

I don't see it transpiling ES6 to ES5. 我看不到它将ES6转换为ES5。

The first example I looked for in your code was the conversion of let to var in the bundled code since this is probably the most commonly used ES6 feature. 我在您的代码中寻找的第一个示例是捆绑代码中letvar的转换,因为这可能是最常用的ES6功能。

With babel-loader, let gets converted to var (and some other fancy maneuvering). 使用babel-loader, let转换为var (以及其他一些有趣的操作)。 Without, it remains let . 没有它,它仍然let

To explore this, I commented out UglifyJS so the bundle was readable and ctrl+f ed the file. 为了对此进行探讨,我注释掉了UglifyJS,以便该包可读且按ctrl+f fed该文件。 You should be able to see this same behavior. 您应该能够看到相同的行为。

If you're expecting import to be converted to require , this won't happen as webpack just reads the file and loads it into the bundle. 如果您希望将import转换为require ,则不会发生这种情况,因为webpack只会读取文件并将其加载到包中。 So, no require & no import appear in the bundle. 因此,捆绑包中没有require ,也没有import This isn't transpilation, though. 但是,这不是移植。 It's just a function of how webpack's bundling process works (searching for & injecting dependencies into the bundle). 这只是webpack捆绑过程如何工作的功能(搜索依赖并将其注入捆绑中)。

Bonus points: 奖励积分:

I would recommend adding your dist directory to .gitignore . 我建议将您的dist目录添加到.gitignore Typically, you don't want your bundled code version controlled. 通常,您不希望控制捆绑的代码版本。 You should rely on your build tools to handle this (you can add webpack to your package.json 's postinstall if you want to simplify the installation for consumers of your project). 您应该依靠构建工具来处理此问题(如果您想简化项目使用者的安装,则可以将webpack添加到package.jsonpostinstall安装中)。

In hindsight, I realize you probably only added the dist directory because I asked to see the bundled code. 事后看来,我意识到您可能仅添加了dist目录,因为我要求查看捆绑的代码。 Sorry! 抱歉! :p But I'll leave this here in case it helps someone else in the future. :p但是我会留在这里,以防将来对其他人有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM