reactjs - Babel 配置文件在 Lerna monorepo 中不起作用

标签 reactjs babeljs lerna monorepo

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

这是到目前为止我的 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,而且我不想弹出我的应用程序。

最佳答案

对于那些感兴趣的人,我的问题只是我的代码没有被转译,而是按原样复制到我的应用程序的 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 中定义时工作正常。

关于reactjs - Babel 配置文件在 Lerna monorepo 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66545987/

相关文章:

babeljs - 为什么不应该在生产中使用 babel-node?

javascript - let 子句期间 Babel 出现意外标记 ':'

node.js - 如何成功锁定 monorepo 中的 Node 模块依赖项?

javascript - import 和 const 有什么区别,在 commonjs 中哪个是首选

reactjs - 使用代码拆分创建 React 组件 UI 库

node.js - Bazel 与 lerna 和 yarn 工作区一起使用

reactjs - 错误 : Child Compilation failed - Module. createRequire 不是函数

javascript - 尝试使用 axios 遵循 AJAX React 教程

javascript - ReactJS 在渲染函数中访问变量超出范围

javascript - 在常量对象中定义所有通量操作类型是常见做法吗?