Search code examples
node.jsnpm-link

using dist folder instead of root for npm package


I created a Node.js package and the files to be referenced by the user of this package reside in a dist folder inside the package.

Now I don't want to use require('my-package/dist/feature') but require('my-package/feature').

I set main and files to this in package.json but when testing the package with npm link locally, I still have to use require('my-package/dist/feature') otherwise I get Cannot find module errors.

package.json:

  "main": "dist",
  "files": ["dist"],

Solution

  • You need an index.js in the root of your package that imports and re-exports the features of your package that you want to make public (i.e. import from another package):

    export { feature1 } from 'feature1';
    export { feature2a, feature2b } from 'feature2';
    export * from 'feature3';
    // etc
    

    You can then import them into other projects as:

    import { feature1, feature2a } from 'my-package';