0

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.

Dave
  • 2,735
  • 8
  • 40
  • 44
  • have you tried this const share = require('./../shared/share.js') ?, Once I encounter same type of issue. add ./ – Amit Shakya May 09 '20 at 18:34
  • Actually I made one example and it worked with this structure. Did u do a `npm i` in app1 and app2? – Aritra Chakraborty May 09 '20 at 18:45
  • It would be better if share.js was not dependent upon modules installed in `app1` and `app2`. It would be better if it can stand on its own. If it has dependencies, then install them in the `shared` directory and then shared.js can load its own dependencies from its own directory. This is how you make an independent and reusable module. – jfriend00 May 09 '20 at 19:09
  • I use git subprojects for this kind of scenario. – YvesLeBorg May 09 '20 at 20:47

1 Answers1

0

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.