javascript - Babel 在构建时给出意外的 token

标签 javascript reactjs webpack babeljs

我正在尝试构建我的 React 库,但 npm build 给出了这个错误。是什么导致了这个错误以及如何解决它?

    src/lib/CircularProfiles.js -> dist/CircularProfiles.js
    SyntaxError: src/lib/Github.js: Unexpected token (14:10)
      12 | class GithubProfileBar extends Component {
      13 |
    > 14 |     state = {
         |           ^
      15 |         totalRepos: 0,
      16 |         totalStars: 0,
      17 |     }

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! react-profiles@0.1.0 build: `rm -rf dist && NODE_ENV=production babel src/lib --out-dir dist --copy-files --ignore __tests__,spec.js,test.js,__snapshots__`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the react-profiles@0.1.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/natesh/.npm/_logs/2018-12-26T03_51_21_931Z-debug.log

我的 .babelrc 文件:

{
    "presets": [
        "es2015",
        "react"
    ]
}

最佳答案

我发现错误是因为旧版本的 babel 无法处理新版本的 React 代码。

修复方法如下:

我的问题是旧的 babel 版本很容易通过安装修复:

npm i -D @babel/plugin-proposal-class-properties \
  @babel/preset-react \
  @babel/preset-env \
  @babel/core \
  @babel/plugin-transform-runtime \

在 .babelrc 文件中:

{
   "presets": [
       "@babel/react" , 
       "@babel/env" , 
   ],
   "plugins": [
       "@babel/plugin-proposal-class-properties"
   ]
}

现在 babel 构建成功了。

关于javascript - Babel 在构建时给出意外的 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53927260/

相关文章:

javascript - 将 Jquery Globalize 与 MVC 5 结合使用

javascript - Replace(),替换一个未指定的值

javascript - 在验证和发送邮件后更改联系表单的 html

reactjs - 如果可能,如何将 MUI 与 Qwik 框架一起使用?

javascript - angularjs 'ng-href' 不工作

javascript - 使用 Redux Saga 每 X 秒发送一次 Action

javascript - 只能更新已安装或正在安装的组件错误。条件渲染

javascript - 捆绑 ES6 文件而不进行转译

javascript - webpack 4 代码拆分和 var 注入(inject)

css - 使用 webpack,为什么要从 JS 源代码导入 CSS 文件而不是像传统那样单独构建 CSS?