Is there any way to import from root in native es module? (nodejs 16)

Viewed 704

This is our project structure:

- project
-     a.js
-     b.js

In a.js I want to import b.js file using root path in the way like this:

import c from '~/b.js';

but not using relative path like this:

import c from '../b.js';

We are using native esmodule, not Babel or Webpack or something, so is there any way?

1 Answers

This is a pretty unusual requirement. Still, node.js does support this

  • through self-referencing a package using its name, so if your project has a package.json with the name my-project, then you can do

    import c from 'my-project/b.js';
    

    from anywhere within your project, not using relative imports

  • through subpath imports, so if you declare a

    …
    "imports": {
        "#b": "./b.js"
    },
    …
    

    in your package.json then you can do

    import c from '#b';
    

This also works in ES modules, see the ESM resolution algorithm (specifically PACKAGE_IMPORTS_RESOLVE). Of course, it does not work without a package.json, as without a package there is no such thing as a "root path" for your project.

Related