[英]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.