bundle.js 使用 babel polyfill 后仍然包含箭头函数和默认参数

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

我添加了很多 Babel 或其他人从堆栈溢出中给出的设置,但 ES6 的新特性,如箭头函数和默认参数仍在我的 bundle.js

bundle.js的内容如下:

    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 中打开我的页面时,发生了指向 function(e={}) 的错误 missing ')'

这是我的 webpack.config.js:

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 用于模块

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:

{
  "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/preset-env 插件中针对特定的浏览器,在babel.config.js 中定义(这是声明 babel 配置的另一种方式)。

    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

{
  "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

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

{
  "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

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 (
            <div onClick={ e => { this.method(e) }}/>
        )
    }
}

export default someComponent;

config/loaders.js

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/'
                }
            }]

        }
    ]
};

在我的例子中,它是由一些包含默认参数的包引起的。所以我通过在 babel-loader:

中包含 node_modules 来解决这个问题

    {
      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 !
    },

我正在使用 webpack 5,在 webpack.config.js 中将目标设置为 es5 解决了我的问题。

module.exports = {
    target: 'es5',
    ...
}