Home > Software engineering >  npm import from same index.js that the current file is exported from
npm import from same index.js that the current file is exported from

Time:12-02

Suppose I have created an npm module named @myscope/blurfl that contains a couple of classes: A, defined in A.js and B defined in B.js, that are both re-exported through blurfl/index.js:

@myscope/
    blurfl/
        A.js
        B.js
        index.js

A.js:

export class A {...}

B.js:

import { A } from './A.js';
export class B {...}

index.js:

export * from "./A.js";
export * from "./B.js";

I would prefer to use import { A } from '@myscope/blurfl' instead of import {A} from './A.js' to keep the code cleaner (and make it easier to move an export into a different file), but @myscope/blurfl is obviously not a dependency of @myscope/blurfl itself, so the node module resolver can't find it if I run node index.js to check for missing dependencies.

Is there any way to import another item co-exported from the same index.js file without using the item's explicit filename?

CodePudding user response:

I'm assuming you are using a current version of Node.js (12 LTS or later). Make sure that the "name" of your package in package.json is really "@myscope/blurfl" (and not just "blurfl"). Now, add an "exports" section to the package.json specifying the relative path of the main export, i.e.

"exports": {
    ".": "./index.js"
}

You should now be able to use import { A } from '@myscope/blurfl' from within your package, too.

So, to summarize:

  • Use Node 12 or later.
  • Check the "name" in package.json.
  • Add an "exports" section to package.json indicating the main entry point export.
  • Related