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?
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With