简体   繁体   中英

Node 14: Import modules using an absolute path for native ES6 module

I am writing an app in node 14.9.0 . I have created an ES6 module by adding "type": "module" to my package.json . I am trying to import modules for my project. I want to avoid using relative imports (because ../../ is so readable) and instead want to use an absolute import as if each module was being imported from the index.js file in the root of my project.

From what I gathered about how node discovers modules, omitting the . from the front of my import path should have made node default to looking for modules from the root of my project. However, it instead tries to look from the root of my hard drive.

...
import User from '/models/user.model';
...
Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\models\user.model' imported from C:\Users\User\Documents\My App\my-app\index.js

I am not using typescript, webpack, babel, or any other transpiler. Is it possible to get an absolute import without them?

Because you missing *.js extension. Its requied for ECMA node modules ( https://nodejs.org/api/esm.html#esm_mandatory_file_extensions ). This will be work (now i am developing in node 14 without Babel):

import User from '/models/user.model.js';

and in root package.json you have to add:

"type": "module"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM