关于react js:使用babel polyfill后,bundle.js仍包含箭头功能和默认参数

bundle.js still contains arrow function and default parameters after using babel pollyfill

我从堆栈溢出中添加了Babel或其他人提供的许多设置,但是ES6的新功能(例如箭头功能和默认参数)仍在我的bundle.js中。

bundle.js的内容如下:

1
2
3
4
5
6
7
8
9
10
11
    var nn = function(e={}) {
        const {baseClasses: t, newClasses: n, Component: r} = e;
        if (!n)
            return t;
        const a = At()({}, t);
        return Object.keys(n).forEach(e=>{
            n[e] && (a[e] = `${t[e]} ${n[e]}`)
        }
        ),
        a
    };

结果,当我在IE11中打开页面时,发生错误missing ')',该错误指向function(e={})

这是我的webpack.config.js:

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
const entries = require("./config/pages").reduce(function(map, page) {
  map[page] = `./src/${page}/index.js`;
  return map;
}, {});

module.exports = {
  mode: 'development',
  entry: ["@babel/polyfill",...entries],

  output: {
    path: path.resolve(__dirname,'dist'),
    publicPath: '/',
    filename: 'myapp/static/js/[name]/bundle.js'
  },
  devtool: 'source-map',
  module: require("./config/loaders"),
  devServer:{
    open: true,
    publicPath: '/',
    historyApiFallback: true,
    disableHostCheck: true
  },
  plugins: [
    new MiniCssExtractPlugin({
        filename:"[name].css",
        chunkFilename:"[id].css"
    }),
    new webpack.ProvidePlugin({
        fetch:"isomorphic-fetch",
    })
  ]
};

和模块

的./config/loaders

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
module.exports = {
  rules: [
    {
      test: /\\.(js|jsx)$/,
      // exclude: /node_modules/,
      loader: 'babel-loader',
    },
    {
      test: /\\.(css|less)$/,
      use: ["style-loader","css-loader","less-loader"]
    },
    {
      test: /\\.(png|jpg|gif)$/,
      use: [
        {
          loader: 'url-loader',
          options: {
            limit: 500, //small than 500 use url, otherwise use base64
            outputPath:'inquiry/static/img/'
          }
        }
      ]
    },
    {
      test: /\\.(woff(2)?|ttf|eot|svg)(\\?v=\\d+\\.\\d+\\.\\d+)?$/,
      use: [{
        loader: 'file-loader',
        options: {
          outputPath: 'myapp/static/fonts/'
        }
      }]

    }
  ]
};

.babelrc:

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
{
 "presets": [
    // ["@babel/env",
    //   {
    //    "targets": {
    //      "browsers":"ie 11"
    //     },      
    //    "useBuiltIns":"usage",
    //    "corejs":"3.0.1",
    //   }
    // ],
    ["@babel/preset-env",
      {
       "useBuiltIns":"entry",
       "corejs":"3.0.1",
      }],
   "@babel/react"
  ],
 "plugins": [
    ["@babel/transform-runtime"],
    ["@babel/plugin-transform-parameters"],
    ["@babel/plugin-transform-arrow-functions"],
    [
     "@babel/plugin-proposal-decorators",
      {
       "legacy": true
      }
    ],
    [
     "@babel/plugin-proposal-class-properties",
      {
       "loose": true
      }
    ],
  ]
}

此外,我已经在我的index.js中导入了'@ babel / polyfill'

PS:我注意到代码中包含ES6功能,它们来自node_modules中的Meterial UI lib,因此我删除了babel loader规则中的exclude: /node_modules/,,但仍然无法正常工作。


就我而言,它是由某些包含默认参数的程序包引起的。所以我通过在babel-loader

中包含node_modules修复了该问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
    {
      test: /\\.(jsx?)$/,
      use: {
        loader: 'babel-loader',
        options: {
          presets: ['@babel/env', '@babel/react'],
          plugins: [
            '@babel/plugin-transform-runtime',
            [
              '@babel/plugin-proposal-class-properties',
              {
                loose: true
              }
            ],
            ['@babel/plugin-proposal-export-default-from'],
            '@babel/plugin-transform-parameters'
          ]
        }
      }
      /** Include the node_modules folder to fix !! **/
      // exclude: /node_modules/         // <== Here is the magic works !
    },

我们针对@ babel / preset-env插件中的特定浏览器,该插件在babel.config.js中定义(这是声明babel配置的另一种方式)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    presets: [
        [
            '@babel/preset-env',
            {
                modules: 'commonjs',
                useBuiltIns: 'entry',
                targets: {
                    chrome: '58',
                    firefox: '54',
                    ie: '11',
                    safari: '10',
                    opera: '44',
                    edge: '16'
                }
            }
        ],
        [
            '@babel/preset-react'
        ]
    ],
    plugins: [
        '@babel/plugin-syntax-dynamic-import',
        '@babel/plugin-proposal-class-properties'
    ]

请尝试我上面发布的目标声明。
我们使用babel / preset-env 7.3.1,它的corejs不是顶级配置选项。

更新

我能够使其与一个测试项目一起使用,我试图尽可能地使其与您的设置相匹配。您可以使用它来缓慢增加复杂性和在项目中使用的模块,以找出问题所在。此基本设置与您的设置相匹配,效果很好。您可以以此为起点。

package.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
{
 "name":"babel-transprile-error",
 "version":"1.0.0",
 "main":"index.js",
 "license":"MIT",
 "dependencies": {
   "@babel/core":"^7.4.3",
   "@babel/plugin-proposal-class-properties":"^7.4.0",
   "@babel/plugin-proposal-decorators":"^7.4.0",
   "@babel/plugin-transform-arrow-functions":"^7.2.0",
   "@babel/plugin-transform-parameters":"^7.4.3",
   "@babel/plugin-transform-runtime":"^7.4.3",
   "@babel/polyfill":"^7.4.3",
   "@babel/preset-env":"^7.4.3",
   "@babel/preset-react":"^7.0.0",
   "@babel/runtime":"^7.4.3",
   "babel-loader":"^8.0.5",
   "mini-css-extract-plugin":"^0.6.0",
   "react":"^16.8.6",
   "react-dom":"^16.8.6",
   "webpack":"^4.30.0",
   "webpack-cli":"^3.3.1"
  }
}

webpack.config.js

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
const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const webpack = require('webpack');

module.exports = {
    mode: 'development',
    entry: ["@babel/polyfill", './src/page/index.js'],

    output: {
        path: path.resolve(__dirname,'dist'),
        publicPath: '/',
        filename: 'myapp/static/js/[name]/bundle.js'
    },
    devtool: 'source-map',
    module: require("./config/loaders.js"),
    devServer:{
        open: true,
        publicPath: '/',
        historyApiFallback: true,
        disableHostCheck: true
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename:"[name].css",
            chunkFilename:"[id].css"
        }),
        new webpack.ProvidePlugin({
            fetch:"isomorphic-fetch",
        })
    ]
};

.babelrc

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
{
 "presets": [
    // ["@babel/env",
    //   {
    //    "targets": {
    //      "browsers":"ie 11"
    //     },
    //    "useBuiltIns":"usage",
    //    "corejs":"3.0.1",
    //   }
    // ],
    ["@babel/preset-env",
      {
       "useBuiltIns":"entry",
       "corejs":"3.0.1",
      }],
   "@babel/react"
  ],
 "plugins": [
    ["@babel/transform-runtime"],
    ["@babel/plugin-transform-parameters"],
    ["@babel/plugin-transform-arrow-functions"],
    [
     "@babel/plugin-proposal-decorators",
      {
       "legacy": true
      }
    ],
    [
     "@babel/plugin-proposal-class-properties",
      {
       "loose": true
      }
    ],
  ]
}

src / page / index.js

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
import React, { Component } from 'react';

class someComponent extends React.Component {

    constructor(props) {
        super(props);
    }

    method(e = {}) {
        console.log(e);

        var nn = function(e={}) {
            const {baseClasses: t, newClasses: n, Component: r} = e;
            if (!n)
                return t;
            const a = At()({}, t);
            return Object.keys(n).forEach(e=>{
                    n[e] && (a[e] = `${t[e]} ${n[e]}`)
                }
            ), a
        };
    }

    render() {
        return (
             { this.method(e) }}/>
        )
    }
}

export default someComponent;

config / loaders.js

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
module.exports = {
    rules: [
        {
            test: /\\.(js|jsx)$/,
            // exclude: /node_modules/,
            loader: 'babel-loader',
        },
        {
            test: /\\.(css|less)$/,
            use: ["style-loader","css-loader","less-loader"]
        },
        {
            test: /\\.(png|jpg|gif)$/,
            use: [
                {
                    loader: 'url-loader',
                    options: {
                        limit: 500, //small than 500 use url, otherwise use base64
                        outputPath:'inquiry/static/img/'
                    }
                }
            ]
        },
        {
            test: /\\.(woff(2)?|ttf|eot|svg)(\\?v=\\d+\\.\\d+\\.\\d+)?$/,
            use: [{
                loader: 'file-loader',
                options: {
                    outputPath: 'myapp/static/fonts/'
                }
            }]

        }
    ]
};


我正在使用webpack 5,并且在webpack.config.js中将target设置为es5为我解决了这个问题。

1
2
3
4
module.exports = {
    target: 'es5',
    ...
}