简体   繁体   中英

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.

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.

So I'd like my component to use the package installed in the app. 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 . 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. Whether or not a peer dependency works here is dependent on the react-i18next implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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