Realistic Realistic - 1 month ago 14
Node.js Question

Make npm package sub-modules available

I have a private library meant to be shared between two code bases.
It is structured like so:

package.json
src/
|_stores/
|_user.js
|_actions/
|_user.js


The project is called "foo", I would like to do imports as follows:

require('foo/stores/user');
// OR
import User from 'foo/stores/user';


What is the best way to do this?

I've read this OP which suggests I can copy the package.json into a
lib
folder but but it lacks further details?

Things I've tried:



Since the code is ES2015/React/Flux I am using
babel
and
gulp
with a prepublish script to build a
lib
directory on
npm install
that looks like so:

package.json
src/
|_stores/
|_user.js
|_actions/
|_user.js
lib/
|_stores/
|_user.js
|_actions/
|_user.js


But, this only makes things available via:
require('foo/lib/stores/user')
so, I changed the prepublish script to build to the parent directory causing this:

package.json
stores/
|_user.js
actions/
|_user.js
src/
|_stores/
|_user.js
|_actions/
|_user.js


But, during local development (using npm link/file dependency) this gets a little messy.

I've also tried symlinking package.json to
lib
and setting
main
to point to
lib
but this didn't appear to do anything.

Answer

As it turns out, what I was trying to do goes against convention. Since writing this question i've noticed the majority of libraries reference their dependencies via package/lib/dep. So in short I did the following as mentioned in the question:

Use webpack (or babel and gulp) with a prepublish script to build a lib directory on npm install that looks like so:

package.json
src/
 |_stores/
     |_user.js
 |_actions/
     |_user.js
lib/
 |_stores/
     |_user.js
 |_actions/
     |_user.js

This will allow you to do the following: require('foo/lib/stores/user')

Comments