gpt4 book ai didi

reactjs - 使用 React 从 monorepo 中的另一个包导入 JSX 文件时出错

转载 作者:行者123 更新时间:2023-12-04 02:28:08 33 4
gpt4 key购买 nike

我创建了一个简单的项目来研究 monorepo。该示例由三个 React 应用程序组成,其中一个包含带有 Storybook 的组件库,另外两个将导入该包的组件。

但是我无法从另一个包中导入组件。当我导入一个普通函数时,没有出现错误。

Github repository

错误信息

../components/src/button/Button.js
SyntaxError: /home/thiago/Documentos/Dev/projects/learn-monorepo/packages/components/src/button/Button.js: Support for the experimental syntax 'jsx' isn't currently enabled (7:5):

5 | function Button({label, ...rest}) {
6 | return (
> 7 | <div>
| ^
8 | <button {...rest}>
9 | {label}
10 | </button>

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.

按钮组件

function Button({label, ...rest}) {
return (
<div>
<button {...rest}>
{label}
</button>
</div>
);
}

export { Button };

应用程序.js

import React from 'react';
import { Button } from '@project/components';

function App() {
return (
<div>
<h1>Hello World - App 01</h1>
<Button label="Button"/>
</div>
);
}

export default App;

包.json

{
"name": "project",
"version": "1.0.0",
"main": "build/index.js",
"author": "thiago <thenrique2012@gmail.com>",
"license": "MIT",
"private": true,
"workspaces": {
"packages": ["packages/*"]
},
"babel": {
"presets": [
"@babel/preset-react"
],
"plugins": [
"@babel/plugin-syntax-jsx"
]
},
"scripts": {
"bootstrap": "lerna bootstrap",
"start:app-01": "lerna run --scope @project/app-01 start",
"start:app-02": "lerna run --scope @project/app-02 start",
"start:storybook": "lerna run --scope @project/components storybook",
"start:web": "yarn start:app-01 & yarn start:app-02 & yarn start:storybook"
},
"devDependencies": {
"@babel/plugin-syntax-jsx": "^7.12.1",
"@babel/preset-react": "^7.12.10",
"babel-loader": "8.1.0",
"lerna": "^3.22.1"
}
}

最佳答案

你得到错误是因为你没有转译你共享的 React 组件。使用 create-react-app 有一些(非官方的)解决方案。其中之一是使用 react-app-rewiredcustomize-cra。将 lthem 安装为开发依赖项并将 config-overrides.js 文件添加到 create-react-app 的根目录:

var path = require('path')
const { override, babelInclude } = require('customize-cra')

module.exports = function (config, env) {
return Object.assign(
config,
override(
babelInclude([
/* transpile (converting to es5) code in src/ and shared component library */
path.resolve('src'),
path.resolve('../components'),
])
)(config, env)
)
}

然后在您的脚本中使用 react-app-rewired 而不是 react-scripts 来启动和构建项目:

"scripts": {
"start": "react-app-rewired start",
"build-prod": "react-app-rewired build",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-scripts eject"
},

关于reactjs - 使用 React 从 monorepo 中的另一个包导入 JSX 文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65890421/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com