使用babel pollyfill

时间:2019-04-24 06:31:09

标签: reactjs webpack babeljs babel-polyfill

我从堆栈溢出中添加了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/,,但仍然无法正常工作。

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

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

Public Sub ConfigureAuth(app As IAppBuilder)

    app.UseCookieAuthentication(New CookieAuthenticationOptions() With {
   .AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    .LoginPath = New PathString("/Login.aspx")})
    app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie)

    app.UseGoogleAuthentication(ConfigurationManager.AppSettings("googleclient_id"), ConfigurationManager.AppSettings("googleclient_secret"))
    app.UseFacebookAuthentication(ConfigurationManager.AppSettings("facebookclient_id"), ConfigurationManager.AppSettings("facebookclient_secret"))
End Sub


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    If IsPostBack Then
        Dim provider = Request.Form("provider")
        If provider Is Nothing Then
            Return
        End If
        ' Request a redirect to the external login provider
        Dim redirectUrl As String = ResolveUrl([String].Format(CultureInfo.InvariantCulture, "~/Login/ExternalLogin.aspx?{0}={1}&returnUrl={2}", IdentityHelper.ProviderNameKey, provider, ReturnUrl))
        Dim properties As AuthenticationProperties = New AuthenticationProperties() With {.RedirectUri = redirectUrl}
        ''Add xsrf verification when linking accounts
        If (Context.User.Identity.IsAuthenticated) Then
            properties.Dictionary.Item(IdentityHelper.XsrfKey) = Context.User.Identity.GetUserId()
        End If
        Context.GetOwinContext().Authentication.Challenge(properties, provider)
        Response.StatusCode = 401
        Response.[End]()
    End If
End Sub

请尝试像我上面发布的那样进行目标声明。 我们使用babel / preset-env 7.3.1,它的 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' ] 不是顶级配置选项。

更新

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

package.json

corejs

webpack.config.js

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

.babelrc

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",
        })
    ]
};

src / page / index.js

{
  "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
      }
    ],
  ]
}

config / loaders.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;

答案 2 :(得分:0)

就我而言,它是由某些包含默认参数的程序包引起的。因此,我通过在node_modules中包含babel-loader来解决此问题:


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