javascript Babel 在构建时给予 Unexpted 令牌

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53927260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 10:20:10  来源:igfitidea点击:

Babel giving Unexpted token while building

javascriptreactjswebpackbabel

提问by Natesh bhat

I am trying to build my react library , and npm build gives this error . what is causing this error and how to fix it ?

我正在尝试构建我的 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! [email protected] 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 [email protected] 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

My .babelrc file :

我的 .babelrc 文件:

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

回答by Natesh bhat

I found that the error is because of older version of babel which doesn't handle newer versions of react code.

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

Here's the fix :

这是修复:

My problem was of older babel version fixed easily by installing :

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

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

In .babelrc file :

在 .babelrc 文件中:

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

Now babel built it successfully after this.

现在 babel 在此之后成功构建了它。

回答by Kim Steinhaug

Make sure you are not using both v7 and v6 branch og babel. The "@babel/core" is the 7x branch and the "babel/core" is the 6x branch, you should not have both installed at once!

确保您没有同时使用 v7 和 v6 分支 og babel。"@babel/core" 是 7x 分支,"babel/core" 是 6x 分支,你不应该同时安装两者!