Import from subfolder of npm package

Can I skip the src/ directory somehow in the import path?

Yes. Using the package.json "exports" field, which should be supported by Webpack in a near future (see this issue), but has already been supported by Node since Node 12 LTS following the Bare Module Specifier Resolution proposal:

package.json

...
"main": "./src/index.js",
"type": "module",
...
"exports": {
  "./Button": "./src/Button/index.js",
  "./Header": "./src/Header/index.js"
},
...

Now, the following code:

// This project is responsible for building/transpiling after importing
import { Button, ButtonGroup } from 'components-library/Button';

should be translated to:

import { Button, ButtonGroup } from 'components-library/src/Button/index.js';

which should correctly import the requested modules.

Caveat

Now, it would certainly be tempting to try a simpler version like:

...
"exports": {
  "./Button": "./src/Button/",
  "./Header": "./src/Header/"
},
...

so as the usual import statement

import { ... } from 'components-library/Button';

gets translated to

import { ... } from 'components-library/src/Button';

This looks nice, but it will not work in this case, because your submodules don’t have each their own package.json file but rely on their index.js file to be found.

/!\ Unlike in CommonJS, there is no automatic searching for index.js or index.mjs or for file extensions.


src/index.js – Is this file actually necessary if only importing from subdirectories?

I don’t think so, but you can keep it if you want.


Can I skip any type of build phase in the package?

Using the "exports" field does not require you to transpile your code.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)