1

I have a library (ES6) which is composed on many sub-modules, say

- package.json
- lib
  - my_package
    - file1.js
    - file2.js
    - sub_module1
      - file3.js
      - file4.js

I currently do imports like this (all inside my package - using file resolution to find, not node_modules resolution):

import {func1} from 'lib/my_package/file1'
import {func3} 'lib/my_package/sub_module1/file3'

So, in practice I have many files across sub-directories.

I am now trying to package and publish my library, which will be installed under node_modules.

It seems to me that the node resolution algorithm (when behind node_modules) only allows for a single entry point (and there is nothing rollup can do about that)

I would like to be able to include many sub directories and files and for them to be resolved individually.

As far as I understand I have to include a single toplevel file that has all the export from machinery. I can only import that single top level file.

This means having to manually create that file. It also means losing the all the sub-module name structuring that comes from the directory structure.

I was wondering: is there any way one can import any other file from a node_module directly?

1 Answers1

3

Node's resolution algorithm only resolves the first part of a module source, so if someone does this...

var foo = require('your-library/subdir/foo.js');

...then Node (or Browserify/Webpack/rollup-plugin-node-resolve) will correctly resolve that to

/path/to/project/node_modules/your-library/subdir/foo.js

The tricky part is that you want to author JavaScript modules, but if someone is using your library in Node then they need CommonJS modules. Rollup can't help you here — you would need to do a one-to-one ESM->CJS conversion for each module. So that means either using Babel, or authoring CommonJS modules in the first place.

Rich Harris
  • 28,091
  • 3
  • 84
  • 99