Ephapox
Ephapox

Reputation: 827

npm multiple entry points

I'm making an NPM package and I'm wondering how you can register multiple entry points so that the user can choose to bring in either the entire library or just a portion that they intend on using.

For example to bring in the whole library:

const mainLib = require('main-lib');

Or bringing just a part of it:

const subLib1 = require('sub-lib-1');
const subLib2 = require('sub-lib-2');

It seemed intuitive to me to have the main property of package.json to accept multiple values but that doesn't seem to be the case according to the documentation.

Upvotes: 18

Views: 11538

Answers (1)

pleup
pleup

Reputation: 917

"main" defines the module to load when you call require(...) with just the package's name. However, you can also require a specific file in that package.

eg with the following package:

- mypackage/
   - main.js   <- "main" in pkg.json
   - moduleA.js
   - src/
     - index.js
     - filaA.js
     - fileB.js
   - package.json

The following is valid:

require( 'mypackage' )           // resolve to main.js
require( 'mypackage/moduleA' )   // resolve to moduleA.js
require( 'mypackage/src' )       // resolve to src/index.js
require( 'mypackage/src/fileA' ) // resolve to src/fileA.js

Upvotes: 26

Related Questions