# Babel辅助代码块引入

https://www.webpackjs.com/loaders/babel-loader/#babel-is-injecting-helpers-into-each-file-and-bloating-my-code

Babel 在处理JS代码时,会引入一些辅助代码,每个文件都会引入一次,这样会造成代码冗余,增大体积

Babel 为编译的每个文件都插入了辅助代码,使代码体积过大!

Babel 对一些公共方法使用了非常小的辅助代码,比如 _extend。默认情况下会被添加到每一个需要它的文件中。

你可以将这些辅助代码作为一个独立模块,来避免重复引入。

# 解决

@babel/plugin-transform-runtime: 禁用了 Babel 自动对每个文件的 runtime 注入,而是引入 @babel/plugin-transform-runtime 并且使所有辅助代码从这里引用。

# 怎么用

  • 下载包
npm i @babel/plugin-transform-runtime -D
1
  • 配置























 



















const path = require("path");

module.exports = {
  entry: "./src/main.js",
  output: {
    path: path.resolve(__dirname, "../dist"), // 生产模式需要输出
    filename: "static/js/main.js", // 将 js 文件输出到 static/js 目录中
    clean: true,
  },
  module: {
    rules: 
        [
          // 其他配置
          {
            test: /\.js$/,
            // exclude: /node_modules/, // 排除node_modules代码不编译
            include: path.resolve(__dirname, "../src"), // 也可以用包含
            use: [
              // 其他配置
              {
                loader: "babel-loader",
                options: {
                  // 其他配置
                  plugins: ["@babel/plugin-transform-runtime"], // 减少代码体积
                },
              },
            ],
          },
        ],
  },
  plugins: [
    // 其他配置
  ],
  optimization: {
    // 其他配置
  ],
  devServer: {
    // 其他配置
  },
  mode: "production",
  devtool: "source-map",
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42