[英]What is the best way to create component library for both React and Preact?
我目前正在从事一个涉及 React 和 Preact 的项目。 我发现我需要为 React 和 Preact 使用相同的组件。
将组件放入 npm 库包中是不是一个好主意。 为 React 和 Preact 创建组件库的可能方法是什么? 期待听到您的想法和讨论。
代码可能如下所示:
反应项目: Home.js
import React from 'react'
import Fancy from 'fancy-component/react' // My <Fancy /> component library
class Home extends React.Component {
render() {
return (
<div>
{/* Other parts of the code run here*/}
<Fancy text='🦄' />
</div>
)
}
}
export default Home
Preact 项目: AnswerPage.js
import { h, Component } from 'preact'
import Fancy from 'fancy-component/preact' // My <Fancy /> component library
class AnswerPage extends Component {
render() {
return (
// Other Preact codes run here again
<Fancy text='🚀 again' />
)
}
}
export default AnswerPage
组件库: fancy-component
const Fancy = ({ text = '' }) => (
<div>
<span>{`This is so Fancy ✨ ${text}`}</span>
</div>
)
export default Fancy
我们最近做了这件事,因为我们在网上找不到太多关于这件事的信息,所以需要反复试验。 这就是我们最终的结果:
文件夹结构:
/apps
/mobile
/desktop
/shared
/components
在 preact 10 中,内置了 preact-compat,因此您不必担心有单独的组件 - 只需像往常一样对共享文件夹中的组件使用 React,preact 将自动正确地为导入设置别名。
就别名而言,我们将其添加到我们的preact.config.js
以便我们可以从 app 目录中导入像@components/Date
这样的@components/Date
config.resolve.alias['@components'] = path.resolve(__dirname, '../../shared/components')
对于 React 应用程序,我可以完成这项工作的唯一方法是在babel.config.js
添加别名, babel.config.js
所示:
['module-resolver', {
alias: {
'@components': '../../shared/components'
}
}]
我希望这可以帮助其他可能陷入困境的人!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.