9

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"],
Alexander Zeitler
  • 11,919
  • 11
  • 81
  • 124
  • 1
    You need an `index.js` in the root of your package that `import`s and re-`exports` the features of your package that you want to make public (i.e. `import` from another package). – axiac Jan 25 '19 at 17:50
  • 1
    `"main": "dist/index.js",` – Yegor Jan 25 '19 at 18:07

1 Answers1

3

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';
axiac
  • 68,258
  • 9
  • 99
  • 134
  • 7
    this shouldn't be the correct answer as it doesn't allow `import something from 'my-package/feature', also not a good practice for tree-shaking – Sh eldeeb Apr 14 '22 at 22:38