【问题标题】:Babel config file not working in Lerna monorepoBabel 配置文件在 Lerna monorepo 中不起作用
【发布时间】:2021-03-09 11:24:57
【问题描述】:

我正在使用 Lerna 构建一个 monorepo,其中包含多个 React 应用程序和一些自定义库(实用程序、UI React 组件等)。

到目前为止,这是我的 monorepo 的结构:

packages
  app1
  app2
  ui-component
  utils

但是当我尝试在我的应用程序中使用我的库时,我遇到了以下两个问题:

    SyntaxError: ...\packages\ui-component\index.js Support for the experimental syntax 'classProperties' isn't currently enabled (2:8):
    
      1 | class Foo {
    > 2 |   name = 'This is Foo'
        |        ^
      3 | }
    
    Add @babel/plugin-proposal-class-properties (https://git.io/vb4SL) to the 'plugins' section of your Babel config to enable transformation.
    If you want to leave it as-is, add @babel/plugin-syntax-class-properties (https://git.io/vb4yQ) to the 'plugins' section to enable parsing.
    SyntaxError: ...\packages\ui-component\index.js: Support for the experimental syntax 'jsx' isn't currently enabled (3:5):
    
      1 | function Foo() {
      2 |   return (
    > 3 |     <div>Foo React Component</div>
        |     ^
      4 |   );
      5 | }
    
    Add @babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation.
    If you want to leave it as-is, add @babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to enable parsing.

错误消息非常明确,我阅读了 Babel 配置文件 here 并安装了 @babel/preset-react@babel/plugin-proposal-class-properties,创建了以下 babel.config.json

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

但由于某种原因,它没有被考虑在内。

我试图把这个文件放在我的 monorepo 的根目录下。我试着把它放在我的包裹里。我试图将其重命名为.babelrc.json。我试图将这些设置放在我的package.json 中的"babel" 部分。无济于事...

注意:我没有任何webpack.config.js,我宁愿不弹出我的应用程序。

【问题讨论】:

  • 你找到解决办法了吗?
  • 是的。我最终发现了我错过了什么。基本上,问题不是来自我的 Babel 配置,它确实可以在 package.json 中定义。我的问题是我的包代码在我的应用程序节点模块中按原样复制。我只是错过了转译步骤。我会在尽快发布的答案中详细说明。

标签: reactjs babeljs lerna monorepo


【解决方案1】:

对于那些感兴趣的人,我的问题只是我的代码没有被转译,而是按原样复制到我的应用程序的 node_modules 文件夹中。 所以,我所做的是:

  1. index.js 移至src/index/js
  2. 将我的package.json 更改为:
{
  "name": "utils",
  "version": "1.0.0",
  "description": "",
  "main": "dist/index.js",
  "scripts": {
    "transpile": "babel src --watch --out-dir dist --source-maps inline --copy-files"
  },
  "author": "",
  "license": "ISC",
  "babel": {
    "plugins": [
      "@babel/plugin-proposal-class-properties"
    ]
  },
  "dependencies": {
    "@babel/cli": "^7.13.10",
    "@babel/plugin-proposal-class-properties": "^7.13.0"
  }
}

然后我运行npm run transpile,我的库代码现在已正确导入到我的应用中。

是的,Babel 配置在 package.json 中定义时可以正常工作。

【讨论】:

猜你喜欢
  • 2020-01-09
  • 1970-01-01
  • 2020-07-30
  • 2019-10-24
  • 2020-01-12
  • 2019-12-27
  • 2021-01-23
  • 2020-12-17
  • 2017-02-15
相关资源
最近更新 更多