简体   繁体   中英

Creating a modular component library package for NPM

I'm currently creating an npm package that will consist of a series of React components that are common to some applications I am maintaining.

My intention is to be able to import this components individually as needed, not all at once. So for instance if I have the components Accordion, DropDown and Widget, but I'm only using one of them, I'd like for only its code to be required.

My understanding is that I would need to be able to do something like

import Widget from 'components/Widget';

Instead of

import {Widget} from 'components';

But I can't get the first version to work. I have not published this package, so I'm using npm link to test it on another application. I'm not even sure what to Google to solve the problem myself, so I'd also appreciate links to relevant documentation on this matter.

Thanks.

So, of course a few minutes after asking my question I resolved the issue:

First, as Yacine Filali commented on my question above, I need to have individual files in order for this to work (this part I had already figured out).

However, I was incorrectly assuming that the root of my package was going to be set to whichever directory my entry file was in. So in package.json I had set

"main": "./lib/index.js"

Incorrectly assuming that the folder structure would be read from there. After altering my configuration to build everything into the root directory it worked perfectly.

(Of course, I'm now working on a better alternative, like generating a package.json for the lib folder)

In your component:

export default Widget

In your index:

export { default as Component } from './Component'

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