Reputation: 20609
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?
Upvotes: 10
Views: 8173
Reputation: 20609
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.
Upvotes: 3
Reputation: 741
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
Upvotes: 3