简体   繁体   中英

Share code between two local node projects

I have the following directory structure

./app1/app1.js
./app1/package.json
./app1/node_modules
./app2/app2.js
./app2/package.json
./app2/node_modules
./shared/share.js

Both app1 and app2 pull in share.js

// app1.js
const share = require('../shared/share.js')

share.js uses a module defined in both app1 and app2's package.json

// share.js
const toml = require('toml')

When running node app1.js

Error: Cannot find module 'toml'

How can I share the share.js file between these apps? I'd prefer not to use symlinks if possible.

One of the solutions that you could use here would be using yarn workspaces .

That would allow you to share your packages across apps so you can have structure like:

- project1
-- package.json (deps for project1)
- project2
-- package.json (deps for project2)
- sharedPackage
-- package.json (deps for shared)
- package.json  (your root of project deps where you define workspaces)

And now you are able to use your shared package as regular dependency!

Somewhere inside you project1/package.json

"dependencies": {
  "sharedPackage": "1.0.0"
}

And use it in project project1/index.js

const shared = require('sharedPackage');
shared.doSomething();

Yarn will know about your dependencies inside of your workspaces, so it will let you include them and do all of the linking without pain. More to that you can even publish your shared package to some package registry (NPM/Github/whatever) and make it just a package.

That will do the work, but if you are looking for some more scalable solution to manage dependencies I'd really recommend to try lerna or rush .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM