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

2

5

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?

Riccio answered 15/10, 2021 at 16:20 Comment(2)
What do you mean by "root path"? You either do './b.js' (a relative path in the same directory) or just 'b.js' (a name to be resolved by nodejs anywhere).Sequester
It's just a example, in my code it is much more complicated than this, like: "../../../../../test.js" rather than "abc/test.js"Manger
S
8

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.

Sequester answered 16/10, 2021 at 16:48 Comment(2)
Okay, the "self-referencing a package using its name" is my solutionManger
How to add intellisense for this in VSCode?Immersionism
C
3

Subpath imports also support using directories, e.g. in order to use

import {UserDao} from "#dao/UserDao.js";

specify in package.json

"imports":
{
  "#dao/*": "./main/dao/*"
}

Note:

  • # prefix is mandatory
  • ./main/dao/* is relative to package.json
Chunk answered 31/3, 2023 at 9:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.