Babel插件类属性 - React箭头函数

4

我正在使用npm运行一个React项目。经过数小时的研究和实验,无论在哪里都说我必须将以下代码添加到我的".babelrc"文件中,但我在我的目录中没有这个文件,也无法创建它:

{
  "plugins": [
    ["@babel/plugin-proposal-class-properties", { "loose": true }]
  ]
}

但是当我运行代码时,会出现以下错误:
ERROR in ./src/components/NavBar/Menu.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /Users/ymoondhra/Desktop/yt-web/src/components/NavBar/Menu.js:
Support for the experimental syntax 'classProperties' isn't currently enabled
 (20:10):
  18 |     }
  19 | 
> 20 |     fast = () => {
     |          ^
  21 |         this.speed = 100;
  22 |     }
  23 | 
Add @babel/plugin-proposal-class-properties (https://git.io/vb4SL) to the 'plugins' 
section of your Babel config to enable transformation.
1个回答

9
在经过3个小时的探索后,我终于找到了问题的解决方案: - 在根目录下创建一个名为"babel.config.js"的文件。 - 在该文件中加入以下内容。 - 重新运行程序(即npm start)。
module.exports = {
  presets: [ "@babel/preset-env", "@babel/preset-react" ],
  plugins: [ "@babel/plugin-transform-arrow-functions", "@babel/plugin-proposal-    class-properties" ]
}

需要额外的设置吗?例如 package.json 文件。 - David Casanellas
我花了很长时间才让它工作。我只是在更改文件名,但是错过了模块导出。好文章。 - Bonomi
它会覆盖 .babelrc 吗? - Arun Ramachandran

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接