简体   繁体   English

如何管理通过 npm 共享的反应组件中的导入和依赖项

[英]How to manage imports, dependencies in react component shared via npm

I'm new to sharing react components and I'd like to know if thing I want to do is even possible.我是共享反应组件的新手,我想知道我想做的事情是否可能。

So I have a button component which changes the language of the app.所以我有一个按钮组件可以改变应用程序的语言。 I have an app which includes multiple react apps in it, and I'd like to share some of the components, this button for example.我有一个应用程序,其中包含多个反应应用程序,我想分享一些组件,例如这个按钮。

import React from 'react';
import { useTranslation } from 'react-i18next';

const LngSwitch: React.FC = () => {
  const { i18n } = useTranslation();

  [...some other functions]

  return <div>[...component body]</div>;
};

export default LngSwitch;

The problem is that I'm using here this translation hook.问题是我在这里使用了这个翻译钩子。 I'd like the shared component to use the i18next package from the app it is installed in because otherwise it is useless.我希望共享组件从它安装的应用程序中使用 i18next package,否则它是无用的。

I mean if I install and bundle "i18next" in my library directory and this bundle will be published, on importing this component in the app, it will have its own i18n config and that's not the point.我的意思是如果我在我的库目录中安装并捆绑“i18next”并且这个捆绑包将被发布,在应用程序中导入这个组件时,它将有自己的 i18n 配置,这不是重点。

So I'd like my component to use the package installed in the app.所以我希望我的组件使用安装在应用程序中的 package。 I hope there is the way to achieve that.我希望有办法实现这一目标。 If not, maybe you have any idea how to share this component to make it work as it should.如果没有,也许您知道如何共享此组件以使其正常工作。

Thanks谢谢

What you're likely looking for is a peer dependency .您可能正在寻找的是peer dependency You can add react-i18next to both your devDependencies and peerDependencies , and your devDependencies version will be used in development, while the peerDependencies version will take the package from the top-level package.json when used as a package. You can add react-i18next to both your devDependencies and peerDependencies , and your devDependencies version will be used in development, while the peerDependencies version will take the package from the top-level package.json when used as a package.

That said, this may not be the best option in this context;也就是说,在这种情况下,这可能不是最佳选择; peer dependencies are usually used with tightly coupled packages like plugins, and give you no control over what the package does besides specifying a version.对等依赖项通常与插件等紧密耦合的包一起使用,除了指定版本外,您无法控制 package 的功能。 Whether or not a peer dependency works here is dependent on the react-i18next implementation.对等依赖项是否在这里起作用取决于react-i18next实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM