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

Posted

技术标签:

【中文标题】bundle.js 使用 babel polyfill 后仍然包含箭头函数和默认参数【英文标题】:bundle.js still contains arrow function and default parameters after using babel pollyfill 【发布时间】:2019-09-13 08:59:26 【问题描述】:

我已经添加了许多 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 中打开我的页面时,发生了错误 missing ')',它指向了 function(e=)

这是我的 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/,,但它仍然不起作用。

【问题讨论】:

【参考方案1】:

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

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

【讨论】:

【参考方案2】:

在我的情况下,它是由一些包含默认参数的包引起的。所以我通过在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 !
    ,

【讨论】:

【参考方案3】:

我们在 @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/'
                
            ]

        
    ]
;

【讨论】:

它不起作用。仍然存在箭头函数和默认参数。 j=(e,t=)=&gt;n=&gt;constwithTheme:r=!1,flip:o=null,name:s=t,u=i()(t,["withTheme","flip","name"]) 如果我不提供corejs版本,npm run deploy会遇到一些错误。错误信息:WARNING: We noticed you're using the `useBuiltIns` option without declaring a core-js version. Currently, we assume version 2.x when no version is passed. Since this default version will likely change in future versions of Babel, we recommend explicitly setting the core-js version you are using via the `corejs` option. 我认为我们没有收到关于 corejs 的错误,因为我们使用了模块 commonjs。我再看看。 能否也查看一下我在package.json中提供的版本号?

以上是关于bundle.js 使用 babel polyfill 后仍然包含箭头函数和默认参数的主要内容,如果未能解决你的问题,请参考以下文章

使用 Webpack 和 Babel 时,关闭压缩的最佳方法是啥?

webpack.config.js

为 react 模板配置 browserify

es6 and typescript

Gulp 和 webpack 的 UglifyJs 错误

webpack 打包压缩 ES6文件报错UglifyJs + Unexpected token punc «(», expected punc «:»(示例代码