[英]What is the best way to create component library for both React and Preact?
I'm currently working on a project which involved both React and Preact.我目前正在从事一个涉及 React 和 Preact 的项目。 I came across to this where I need to use same component for React and Preact.
我发现我需要为 React 和 Preact 使用相同的组件。
Is it a good idea to put the component into npm library package.将组件放入 npm 库包中是不是一个好主意。 What are the possible way to create component library for both React and Preact?
为 React 和 Preact 创建组件库的可能方法是什么? Looking forward to hear your ideas and discussions.
期待听到您的想法和讨论。
The code might look like as the following:代码可能如下所示:
React Project: Home.js
反应项目:
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 Project: AnswerPage.js
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
Component library: fancy-component
组件库:
fancy-component
const Fancy = ({ text = '' }) => (
<div>
<span>{`This is so Fancy ✨ ${text}`}</span>
</div>
)
export default Fancy
We did this very thing recently, and because we could not find much information regarding this online it involved quite a bit of trial and error.我们最近做了这件事,因为我们在网上找不到太多关于这件事的信息,所以需要反复试验。 This is what we ended up with:
这就是我们最终的结果:
Folder Structure:文件夹结构:
/apps
/mobile
/desktop
/shared
/components
With preact 10, preact-compat is built in so you don't have to worry having separate components - just use React as normal for the components in your shared folder and preact will automatically alias the imports correctly.在 preact 10 中,内置了 preact-compat,因此您不必担心有单独的组件 - 只需像往常一样对共享文件夹中的组件使用 React,preact 将自动正确地为导入设置别名。
As far as aliasing goes, we added this into our preact.config.js
so that we can import the components like @components/Date
from the app directory就别名而言,我们将其添加到我们的
preact.config.js
以便我们可以从 app 目录中导入像@components/Date
这样的@components/Date
config.resolve.alias['@components'] = path.resolve(__dirname, '../../shared/components')
For the React app, the only way that I could make that work was to add the aliasing in the babel.config.js
like so:对于 React 应用程序,我可以完成这项工作的唯一方法是在
babel.config.js
添加别名, babel.config.js
所示:
['module-resolver', {
alias: {
'@components': '../../shared/components'
}
}]
I hope that this helps someone else that might be stuck on this!我希望这可以帮助其他可能陷入困境的人!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.