DEV Community

Bartosz Pietrucha for Angular

Posted on

[Pro Tip] `npm link` explained πŸŽ‰

It's time for another Angular Knowledge Pill!
It takes just a couple of seconds to learn something new πŸ”₯
Like taking your morning vitamins πŸ˜ƒ

If you are working on a library that you want to import to your application you don't have to publish it to any npm repository! You can link it locally. Imagine you develop an Angular library or maybe you have your CSS theme in a separate npm package that you want to import to your application locally. You can use npm link command like below. 😎

Alt Text

npm link creates a symbolic link (symlink) from your <global node_modules> directory to the local library’s directory.

npm link <library-name> creates a symbolic link from project's local node modules directory ./node_modules/<library_name> to <global_node_modules>/<library_name>.

To locate your <global node_modules> directory, type npm root -g in the command line.

Now, you can import your library directly in your application like below. But, there is a catch! 😱

Alt Text

The catch is that you need one more change in your angular.json file! You need to add a property preserveSymlinks as presented below. And that's it! You can run your application with the local dependency! πŸ”₯

Alt Text


If you would like to receive this kind of knowledge pills directly into your mailbox, subscribe at angular-academy.com/blog/. I will be sending them regularly! Remember, it just takes 10 seconds to learn something new! πŸ˜ƒ

Top comments (6)

Collapse
 
briancodes profile image
Brian • Edited

If you do this often it can become difficult to recall what packages you linked, or whether you've linked a particular library. You can find them all with

npm list -g --depth=0 --link=true
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dariopiotrowicz profile image
Dario Piotrowicz

This is great! Thanks a lot!

It worked perfectly for my project, I have tried this in the past but wasn't able to make it work, I suspect I wasn't aware of the preserveSymlinks option that needed to be set, but by following your blog it all went smoothly this time around :)

One thing to mention is that my application lags a bit behind and is using angular 5, in that I think that the option is not settable, so instead I simply need to use the --preserve-symlinks when serving it

Collapse
 
bartosz_io profile image
Bartosz Pietrucha

Great! πŸ’ͺπŸ’ͺπŸ’ͺ

Collapse
 
penguintheorem profile image
Attilio Urbani

Hello!

your hint fixed one of my issues.. I couldn't make the library working outside applications defined in the same workspace.

Thanks!

Collapse
 
warrenlafrance profile image
Hexa

So do you run the "npm link" in the root or the dist or ??

Collapse
 
bartosz_io profile image
Bartosz Pietrucha

You are welcome!