'Still "Error [ERR_MODULE_NOT_FOUND]: Cannot find module" After adding "type":"module"
I know this is require / import ES6 thing. I have a project using import and files are all .js, based on this all I need is adding "type":"module" into nearest package.json. This is my package.json at the same top level as server.js and env.js:
{
"name": "my project",
"version": "1.0.0",
"description": "many .js",
"main": "server.js",
"type":"module",
"directories": {
"test": "test"
},
"dependencies":{...},
"devDependencies":{...},
"scripts":{...},
"author":"John Doe"
}
server.js
import express from 'express';
import 'babel-polyfill';
import cors from 'cors';
import env from './env';
Still got
internal/process/esm_loader.js:74 internalBinding('errors').triggerUncaughtException( ^ Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'c:\project\env' imported from c:\project\server.js did you mean to import../env.js?
node is 14.9.0, using nvm.
launch.json
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}\\server.js"
}
]
}
Solution 1:[1]
From the docs of Node.js, "There is the ECMAScript module loader:", fifth point:
It does no extension searching. A file extension must be provided when the specifier is a relative or absolute file URL.
So you will need to change one line:
import express from 'express';
import 'babel-polyfill';
import cors from 'cors';
// import env from './env';
import env from './env.js';
as the error message already hint you:
[...] did you mean to import../env.js?
Solution 2:[2]
If you do "type":"module", then you can't import things like import env from './env';
You just need to do it as written below:
import env from './env.js';
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | VimNing |
| Solution 2 | Alish Madhukar |
