Can i use npm link to attach React components?

Viewed 2978

I have two separate projects both scaffolded with create-react-app. First on - UI contains simple ui library. It's just a bunch of simple components with project structure like this:

app
 src
   CustomButton.js
   ...

Nothing unusual. Just a bunch of simple react components. And the second one is application itself.

Is it possible to use npm link to add UI project as dependency? I want to be able to import components from UI project like this:

import {CustomButton} from 'UI';
1 Answers

Yes, I do this quite often. From the npm link docs:

Package linking is a two-step process.

First, npm link in a package folder will create a symlink in the global folder {prefix}/lib/node_modules/ that links to the package where the npm link command was executed. It will also link any bins in the package to {prefix}/bin/{name}. Note that npm link uses the global prefix (see npm prefix -g for its value).

Next, in some other location, npm link package-name will create a symbolic link from globally-installed package-name to node_modules/ of the current folder.

Note that package-name is taken from package.json, not from directory name.

Example:

cd ~/projects/my-components-lib  # go into the package directory
npm link                         # creates global link
cd ~/projects/my-app             # go into some other package directory.
npm link my-components-lib       # link-install the package
Related