[英]How to package a react component on npm without store
I've been reading articles about how to publish react components to NPM, but I'm confused about the details when the component has a store implemented using a library like mobx.我一直在阅读有关如何将 React 组件发布到 NPM 的文章,但是当组件具有使用像 mobx 这样的库实现的存储时,我对细节感到困惑。 Take a simple example like the component you can see in its entirety here :举一个简单的例子,比如你可以在这里完整看到的组件:
const App = () => {
const store = useLocalStore(() => ({
data: initialData,
index: 0,
addRow() {
if (this.index < this.data.length) {
this.data = [...this.data, addData[this.index++]];
}
}
}));
return useObserver(() => (
<div className="App">
<MaterialTable
columns={columns}
data={store.data}
title="Sample Material Table"
/>
<Button onClick={store.addRow}>Add Row</Button>
</div>
));
};
This example uses MobX, where useObserver
and useLocalStore
are specific to that library.此示例使用 MobX,其中useObserver
和useLocalStore
特定于该库。 I personally am choosing to use MobX.我个人选择使用 MobX。 Let's say I publish this to NPM and use it in another project that prefers to use some other state management library.假设我将它发布到 NPM 并在另一个更喜欢使用其他状态管理库的项目中使用它。 I think what I have here is confusing in that scenario, and furthermore I'm not sure it would even work at all--or maybe it would... I don't know.我认为我在这种情况下所拥有的东西令人困惑,而且我不确定它甚至会起作用 - 或者它可能会......我不知道。
The question is simple: how should I put this component together in such a way as to work with any state management library?问题很简单:我应该如何将这个组件组合在一起,以便与任何状态管理库一起使用?
Let's say you want to use mobx
and default react hooks
as two different types of state management for your component.假设您想使用mobx
和默认react hooks
作为组件的两种不同类型的状态管理。
Solution 1:解决方案1:
First, make mobx
a peer dependency of your library, then structure your package in way that the end-user could use (import) your library like this:首先,使mobx
成为您的库的对等依赖项,然后以最终用户可以像这样使用(导入)您的库的方式构建您的包:
//for regular (default) usage with hooks
import myComponent from 'package-name/hooks'
// for mobx version
import myComponent from 'package-name/mobx'
In any case, you need to separate the usage of different state libraries, and internally try to reuse (share) as much code as possible when creating your library.在任何情况下,您都需要分离不同状态库的使用,并在创建库时在内部尝试重用(共享)尽可能多的代码。
Solution 2:解决方案2:
Publish two (or maybe even three) different packages under the same npm scope eg @myLib/mobx
and @myLib/hooks
and possibly a third package that has the code that is shared between all the packages @myLib/default
在相同的npm 范围内发布两个(甚至三个)不同的包,例如@myLib/mobx
和@myLib/hooks
,可能还有第三个包,其代码在所有包@myLib/default
之间共享
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.