Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import local npm package using scope

My monorepo:

/app1
  package.json
/app2
  package.json
/shared
  package.json

The shared/package.json has "name": "@company/shared".

The app projects' package.json files have dependecy "@company/shared": "file:../shared".

When referencing the shared code, I want a "short" style, which is also less liable to break when things are moved around:

import { foo } from "@company/shared"

But that doesn't work, so I have to do this::

import { foo } from "../../../../../shared/src/something"

I fiddled with both package.json and tsconfig.json without success.

How do I set that up?

like image 619
lonix Avatar asked Mar 31 '19 10:03

lonix


People also ask

What is scope in npm package?

Scopes are a way of grouping related packages together, and also affect a few things about the way npm treats the package. Each npm user/organization has their own scope, and only you can add packages in your scope. This means you don't have to worry about someone taking your package name ahead of you.


2 Answers

You should link your shared package to your dependent packages using npm-link.

cd ~/shared                 # go into the package directory
npm link                    # creates global link
cd ~/app1                   # go into some other package directory.
npm link @company/shared    # link-install the package

this will tell npm to install the package from the shared folder, and update with any changes made to the original package

for more info see https://docs.npmjs.com/cli/link.html

EDIT: I have realized only now that you are planning to upload the shared package to the server. in that case you may use the module-alias package, https://www.npmjs.com/package/module-alias

this will allow you to make imports such as const sharedModule = require('@shared/moduleName');

EDIT #2: For typescript, use https://www.npmjs.com/package/tsconfig-paths

like image 195
Marik Sh Avatar answered Sep 23 '22 01:09

Marik Sh


Actually there is a part missing from my code above.

The shared project needs to export the shared stuff in an index.js (i.e. a "barrel" file) and reference that in the package.json:

"main": "dist/index.js",
"types": "dist/index.d.ts",

And then the alias import style works.

like image 32
lonix Avatar answered Sep 23 '22 01:09

lonix