ErrorwhenimportingJSXfilesfromanotherpackageinmonorepowithReact
I created a simple project to study monorepo. The example consists of three React applications, where one consists of a lib of components with the Storybook and the other two will import the components of this package.
但是我无法从另一个包中导入组件。当我导入一个常用函数时,没有发生错误。
Github 存储库
错误信息
../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.
../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
回答
您会收到错误消息,因为您尚未转换共享的 React 组件。有一些(非官方)解决方案可以解决这个问题create-react-app。其中之一是使用react-app-rewired和customize-cra。将它们安装为 dev-dependency 并将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"
},
THE END
二维码