【问题标题】:Unexpected token { with Webpack 4 and @babel/preset-env意外的令牌 { 使用 Webpack 4 和 @babel/preset-env
【发布时间】:2018-12-19 12:50:07
【问题描述】:

这是我的.babelrc

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ]
}

这就是错误的来源。 \client\src\components\AddBook.js:

const { handleSubmit, pristine, reset, submitting } = this.props;

错误信息

   11 |   }
   12 |
 > 13 |   const { handleSubmit, pristine, reset, submitting } = this.props;
      |         ^
   14 |
   15 |   const handleSubmit = (allValues) => {
   16 |     console.log('formData:', allValues);

我认为@babel/preset-env 处理了所有最新的 JavaScript 语法。是什么让代码中断? 完整的 repo 在https://github.com/ElAnonimo/booklist

【问题讨论】:

    标签: ecmascript-6 babeljs webpack-4 babel-preset-env


    【解决方案1】:

    您的.babelrc 没有明确定义它应该为哪些浏览器/版本转译代码。

    根据您的需要调整以下示例.babelrc

    {"presets": [
        [ "@babel/preset-env", {
          "targets": {
            "browsers": ["last 1 version", "ie >= 11"]
          },
          "@babel/preset-react"
        ]
    ]}
    

    https://babeljs.io/docs/en/babel-preset-env#targets

    另外,在使用 webpack 时,您需要明确告诉 babel-loader 尊重 .babelrc 及其所在位置。

    loader: 'babel-loader',
    options: {
      babelrc: path.join(process.cwd(), './babelrc')
    }
    

    ,假设.babelrc 位于您项目的根目录中。

    【讨论】:

    • 谢谢。我已将.babelrc 调整为{ "presets": [ [ "@babel/preset-env", { "targets": { "browsers": ["last 2 versions", "Firefox >= 50"] } }, "@babel/preset-react" ] ] } 我在Firefox 50 上。现在得到[1] 3 | import App from './components/App'; [1] 4 | [1] > 5 | ReactDOM.render(<App />, document.getElementById('app')); [1] | ^ 它在<App /> 中抱怨<
    • 这和 webpack 配置中的loader: 'babel-loader' 有关系吗?
    • 您需要明确告诉babel-loader 尊重.babelrc 及其所在位置。 loader: 'babel-loader', options: { babelrc: path.join(process.cwd(), './babelrc') }, asumming .babelrc 在你项目的根目录中。
    猜你喜欢
    • 2018-01-29
    • 1970-01-01
    • 2017-12-10
    • 2019-09-16
    • 2016-07-10
    • 2019-10-08
    • 2016-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多