How to distribute an es6 package with submodules

Viewed 289

I am trying to publish a package on npm. I'm not sure how to phrase what I am trying to do..maybe packaging "sub modules"?

The abbreviated directory structure is:

- package.json
- src/
  - a.js
  - b.js
- dist/
  - a.js
  - b.js

My build script uses Babel to transpile to the dist directory with the same modules as in src/. I would like consumers to import functions from the a.js module like so:

import {foo} from "mypackage/a";

not

import {foo} from "mypackage/dist/a";

If I add an index.js to mypackage/ and export a I can do

import {a} from "mypackage"

but that's not what I want...

What is the standard way to publish packages so "sub modules" can be imported like this or can someone point me to a repo that does this kind of thing?

1 Answers

If I understand, there should be two options that you can choose.

First, let me try to explain how Node sub-modules with a slash are handled by Node. When you import the module with a slash, Node will try to look in the root folder for a file with the name that is specified after the slash. In your case, it will be a.js. In case nothing is found, Node will try to look for the directory named a containing the file index.js. If no file is found, nothing is imported.

So back to your problem, you can either create file a.js in your root folder containing the following export:

export * from './dist/a';
// The traditional export should look like this, in case I have wrong ES6 export
module.exports = require('./dist/a')

or change the structure of your project a bit, so files a and b are located in their specific directories.

For example:

- package.json
- src/
  - a.js
  - b.js
- a/
  - index.js
- b/
  - index.js
Related