"type": "module" in package.json throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath) - node.js

I want to use import in my nodejs project instead of using require.
So, I added,
"type": "module"
in my package.json.
import index from './index.js';
in server.js
when I run
node server.js
Error says,
internal/modules/cjs/loader.js:1174
throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
^
throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
^
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: ....
server.conf.js is pasted below.
import express from 'express';
import http from 'http';
let app = express();
let server = http.createServer(app);
import morgan from 'morgan';
import methodOverride from 'method-override';;
import path from 'path';
let port = process.env.PORT || 4000;
app.use(morgan('dev'));
app.use(methodOverride('X-HTTP-Method-Override'));
let router = express.Router();
import routes from '../app/routes';
routes(app, router, client);
server.listen(port);
console.log(`Wizardry is afoot on port ${port}`);
export {
app,
client
};

For my case I downgrade:
node-fetch ^3.0.0 → ^2.6.1
Problem solved.

According to stack-trace before you edit (https://stackoverflow.com/revisions/61558835/1):
internal/modules/cjs/loader.js:1174
throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
^
throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
^
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: H:\WORKSPACE\CMDs\node-basic\server.conf.js
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1174:13)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47 {
code: 'ERR_REQUIRE_ESM'
}
I tried to locate the Node src who throws this error:
https://github.com/nodejs/node/blob/c24b74a7abec0848484671771d250cfd961f128e/lib/internal/modules/cjs/loader.js#L1234
// Native extension for .js
Module._extensions['.js'] = function(module, filename) {
if (filename.endsWith('.js')) {
const pkg = readPackageScope(filename);
// Function require shouldn't be used in ES modules.
if (pkg && pkg.data && pkg.data.type === 'module') {
// ...
throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
}
}
// ...
};
The comment Function require shouldn't be used in ES modules tells the js file to be loaded is an ES module, but the caller is trying to use require() function to load it.
Moreover, a double-check into Node src https://github.com/nodejs/node/blob/6cc94b2d7f69f1f541f7c5de3cb86e569fbd4aa3/lib/internal/errors.js#L1319 proves that H:\WORKSPACE\CMDs\node-basic\server.conf.js is the ES module to be loaded.
So I'm trying to guess who is trying to load server.conf.js in your app but no luck. Most likely there is a require('./server.conf.js') in your index.js or somewhere else. If you find it just change it into import to fix.

Had the same issue. I installed the latest node version and then it worked. Try the same. Also if you are using windows make sure it is the correct version i.e 64-bit, 32-bit.

in my case i had a data file (data.js) with products listed as objects inside an array. looked like this :
const data={
products:[
{
brand:'nike',
price:1200
},
{
brand:'adidas',
price:1400
}
]
}
export default data
THE ERROR was caused because i FOOLISHLY exported it like it was a function or class
and wrote:
export default data={
etc...
}
i DOUBT this is a case of your error BUT it shows nonetheless how cumbersome and often this error can show up. if its any clarity what im trying to say im basically saying that this usually shows up due to a file itself being unreadable from import. if you put "type": "module" then it is def a version of node, OR a problem on a base level with something you are trying to import. try deleting each of the imports one by one initially to see which one may be the cause. then work from there

Nothing fancy needed. Just update the Node.js version.

Check your NodeJS version for module compatibility("type": "module"), there are known issues on certain versions.
Most likely there is a require('./server.conf.js') in your index.js/server.js or in the dependent packages you are importing or somewhere else. If you find it just change it into import to fix.
1- Check you're all require statements
2- analyze dependent packages for a require statement in that code
Try a build ...
Try to deploy to NodeJS containers on GC, DO, AWS or HKU

I was also facing similar issue.
So I downgrade chalk module version from 5.0.1 to 4.1.0.
It worked for me.

In my case I was running Angular 13.X och Nx 14.X but my Node version was still 12.X so upgrading the Node version to ^14 solves the problem.

I updated the terminal node version to 16, deleted node_modules and installed it again. And fixed.

Related

my code does not run with the index.js file only with index.mjs > Node.js

good guys I'm still learning and since I'm facing this type of error, I don't know what to do for the code to accept calling as index.js, should I be worried about that? all files i have to change the file to "index.mjs" to work correctly. what I would like to know is if I should accept this or do I have to fix it to run as index.js could you tell me if there is a problem with everything being in mjs?
const inquirer = require('inquirer')
const chalk = require('chalk')
inquirer.prompt([
{name: "p1", message: `${chalk.green("what is your first name: ")}`},
{name: "p2", message: `${chalk.green("what is years old: ")}`}
])
.then((answers) => {
console.log(`${chalk.yellow(answers.p1, answers.p2)}`)
const infoName = answers.p1
const infoAge = answers.p2
console.log(`his name is ${chalk.red(infoName)} and your age is ${chalk.red(infoAge)} years old`)
}).catch((err) => {
console.log(err)
})
this is the error that appears when I try to run with the index.js file
Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\Odin\OneDrive\Área de Trabalho\nodejs tarefas\Fundamentos\node_modules\inquirer\lib\inquirer.js from C:\Users\Odin\OneDrive\Área de Trabalho\nodejs tarefas\Fundamentos\index.js not supported.
Instead change the require of inquirer.js in C:\Users\Odin\OneDrive\Área de Trabalho\nodejs tarefas\Fundamentos\index.js to a dynamic import() which is available in all CommonJS modules.
at Object.<anonymous> (C:\Users\Odin\OneDrive\Área de Trabalho\nodejs tarefas\Fundamentos\index.js:1:18) {
code: 'ERR_REQUIRE_ESM'
}
Node.js v18.13.0
baixei a versão mais recente,
The reason for this is that inquirer is a pure-ESM package.
What is ESM?
Node.js appeared long before import/export support in JS. So it's used (and still is) so called require.js for imports.
Later, Node.js added support for ES modules, but with some limitations. One of these limitations is that ESM script can only be imported from another ESM script.
What to do?
The Node.js ecosystem is slowly migrating to the ESM. So you can continue using ESM, but you should avoid using require and use import instead. E.g.:
import inquirer from 'inquirer';
If you want to use require, you have to downgrade inquirer to version 8+
You can also use TypeScript with esModuleInterop and always use import/export.

Error [ERR_REQUIRE_ESM]: require() of ES Module ... not supported

I'm making a discord bot in TypeScript using discord.js. When I tried to compile code this morning I got this error:
C:\SECRET\Kostegator\dist\Util\getMeme.js:17
const node_fetch_1 = __importDefault(require("node-fetch"));
^
Error [ERR_REQUIRE_ESM]: require() of ES Module C:\SECRET\Kostegator\node_modules\node-fetch\src\index.js from C:\SECRET\Kostegator\dist\Util\getMeme.js not supported.
Instead change the require of index.js in C:\SECRET\Kostegator\dist\Util\getMeme.js to a dynamic import() which is available in all CommonJS modules.
at Object.<anonymous> (C:\SECRET\Kostegator\dist\Util\getMeme.js:17:38)
at Object.<anonymous> (C:\SECRET\Kostegator\dist\Util\index.js:15:14)
at Object.<anonymous> (C:\SECRET\Kostegator\dist\Commands\BotOwner\startAutoUpdate.js:4:16)
at C:\SECRET\Kostegator\dist\Client\index.js:61:41
at Array.forEach (<anonymous>)
at ExtendedClient.<anonymous> (C:\SECRET\Kostegator\dist\Client\index.js:58:48)
at Generator.next (<anonymous>)
at C:\SECRET\Kostegator\dist\Client\index.js:27:71
at new Promise (<anonymous>)
at __awaiter (C:\SECRET\Kostegator\dist\Client\index.js:23:12)
at ExtendedClient.init (C:\SECRET\Kostegator\dist\Client\index.js:51:16)
at Object.<anonymous> (C:\SECRET\Kostegator\dist\index.js:19:4) {
code: 'ERR_REQUIRE_ESM'
}
Here's the GitHub repo: Kostegator
The current version of node-fetch is ONLY compatible with an ESM import (using import), not from CommonJS modules using require().
You have these choices to fix:
Switch your project to an ESM module and load it with import fetch from 'node-fetch';.
In a very recent version of nodejs, you can dynamically import an ESM module into a CommonJS module using let fetch = await import('node-fetch').
Use the v2 version of node-fetch that still supports being loaded with require() as explained here in the doc.
With the latest update, node-fetch only works by using import
You could just install the older version of it by
npm i node-fetch#2.6.1
For those coming here trying to deploy a NodeJS App using the cPanel feature, remember that under the hood it uses Phusion Passenger. This tool needs to have a non-module entry point like:
// entry.cjs DONT FORGET TO USE .cjs and not .js
async function loadApp() {
const { app } = await import("./app.js"); // this is your normal entry file - (index.js, main.js, app.mjs etc.)
}
loadApp()
The original answer is here (it deserves your vote): https://stackoverflow.com/a/71901828/14515077

Issue With Trying to Import a Local File in Node v14.15.1

I am trying to import a local file from my project's directory to my server.js. The directory structure is like this:
server
node_modules
server.js (error occurs here)
src
models
api
controllers
routes
posts.js (trying to import this file, edited to show actual filename)
Here's the error it throws
internal/process/esm_loader.js:74
internalBinding('errors').triggerUncaughtException(
^
Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'E:\ReactProjects\memoirs\server\src\api\routes\posts'
imported from E:\ReactProjects\memoirs\server\server.js
Did you mean to import ../src/api/routes/posts.js?
at finalizeResolution (internal/modules/esm/resolve.js:276:11)
at moduleResolve (internal/modules/esm/resolve.js:699:10)
at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:810:11)
at Loader.resolve (internal/modules/esm/loader.js:85:40)
at Loader.getModuleJob (internal/modules/esm/loader.js:229:28)
at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:51:40)
at link (internal/modules/esm/module_job.js:50:36) {
code: 'ERR_MODULE_NOT_FOUND'
}
[nodemon] app crashed - waiting for file changes before starting...
and my server.js file:
import express from 'express';
import posts from './src/api/routes/posts'; // is there a problem with this file path?
const app = express();
app.use('/api/v1/posts', posts); // error seems to be here, server works if commented out
app.listen(3004, (err)=>{
if(err){
console.log(err);
}
console.log('server at port 3004');
});
The issue seems to be with the file path. I have tried re-arranging it but for some weird reason can't load that particular file into server.js Is there any clear explanation for why this is happening and how to rectify it? Thanks.
It seems like you made a typo. You wrote posts instead of post.
import post from './src/api/routes/post';
EDIT: Seeing that this was just a typo in the question, here is something you could try t fix it:
I would rely on CommonJS Require rather than ES6 Imports on this one, because you can specify relative paths easily by utilizing __dirname:
let express = require('express');
let posts = require(__dirname + '/src/api/routes/posts.js');
I've finally solved this! I got clue from react which throws exact error on not writing .js while importing. You must write extension of even a .js file for node 14+ if you are using type: 'module' in package.json.
Check this image
Solution
So the solution is edit the second line of server.js,
from
import posts from './src/api/routes/posts'
to
import posts from './src/api/routes/posts.js'

How to resolve fs.existsSync is not a function

In NodeJS I have:
const fs = require('fs');
if (!fs.existsSync("some_path")) {
...
}
But I get the error:
TypeError: fs.existsSync is not a function
After doing some searching, I read that Webpack brings its own require which clobbers node.js's require, so when you require a node.js core module that webpack can't resolve to one of your files or dependencies, it throws.
(My stack trace includes __webpack_require__)
But how can I fix it?
I was facing the same Error like TypeError: fs.existsSync is not a function
So, I figured out that one extra line was added automatically which was creating this issue in import.
after removing this line from import
import { TRUE } from "node-sass";
the issue has been resolved.
I had the same error that you have. Your vscode might have added a new module to your js file. Remove that module and your app should work just fine.
You can allow webpack to use the Node's require and include fs etc. by targeting node in the config:
module.exports = {
entry: './src/main.js',
target: 'node',
output: {
path: path.join(__dirname, 'build'),
filename: 'backend.js'
}
}
As described here: https://webpack.js.org/concepts/targets/ and https://webpack.js.org/configuration/target/
I was working on an electron application, I wanted to send a message from node and get in on the react side, but I was having that same issue when requiring ipcRenderer from electron, I tried
import { ipcRenderer } from 'electron';
and
const { ipceRenderer } = require('electron') This leads to an error due to webpack transforming node's require to its own webpack_require. See more info here
What worked for me was to use
const {ipcRenderer} = window.require('electron'); on the react side/renderer side from electron
In my case, I forgot that I'd only imported the promises API, const fs = require("fs").promises, which doesn't have exist or existsSync functions in Node 17.4.0.
To use exist or existsSync, make sure you've imported fs using the sync API (const fs = require("fs")).
Note: I'm adding this answer as a possible solution for future visitors to a canonical thread for the error, not OP who appears to have required fs correctly.
It is nothing to worry about, check your code for something like import { types } from "node-sass";, it would have mistakenly and automatically imported without you know. Remove that line, and everything should work perfectly.
Even if it is not type, it is something from node-sass in your node_modules file, and you can't edit that file.
So look for and remove import { types } from "node-sass"
In my case VSCode added a arbitrary import from electron. After removing it my application worked.
import { Menu } from 'electron';
In my case, i needed to send a message from the node to react. I tried importing ipcRenderer from 'electron'; and const ipceRenderer = require('electron') This results in an error owing to webpack changing the node's require to its own webpack require. See more info here

What is the current simplest way to use ES6 / Import statements etc in Node v 10

I'm fairly new to nodejs. With the evolution of nodejs ( I have just installed v.10 ) what is the current simplest way to use ES6 features ( import statements etc ) in a new nodejs project - that "just works" . I want the least dependencies and the method with the fastest path to "just works".
I am finding the posts on the web a bit confusing.
Babel was installed previously for this sort of thing I understand
Node 10 Says ( Here ) enable using node --experimental-modules my-app.mjs
This post seems quite authoritative , but I think it's about creating packages more than using the syntax.
Please help! I seem to get the following errors for;
import {MagentoAccountApi} from 'js-magento-client';
Error 1:
SyntaxError: Unexpected token {
at new Script (vm.js:74:7)
at createScript (vm.js:246:10)
at Object.runInThisContext (vm.js:298:10)
at Module._compile (internal/modules/cjs/loader.js:646:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:689:10)
at Module.load (internal/modules/cjs/loader.js:589:32)
at tryModuleLoad (internal/modules/cjs/loader.js:528:12)
at Function.Module._load (internal/modules/cjs/loader.js:520:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:719:10)
at startup (internal/bootstrap/node.js:228:19)
If I try renaming the file to have an extension .mjs and load using: node --experimental-modules .\mtest.mjs , then I get this error:
(node:20224) ExperimentalWarning: The ESM module loader is experimental.
file:///F:/node/magento-test/mtest.mjs:1
import {MagentoAccountApi} from 'js-magento-client';
^^^^^^^^^^^^^^^^^
SyntaxError: The requested module 'js-magento-client' does not provide an export named 'MagentoAccountApi'
at ModuleJob._instantiate (internal/modules/esm/module_job.js:89:21)
I don't know if that is a packagage error , or a setup error.
Maybe Babel is still the right / easiest way to make this work..? I guess I don't want to start using something the is going to be deprecated soon.
At present, with the experimental loader, CommonJS interoperability only allows for a single default export. You can't use named exports with existing CommonJS modules, so currently you have to do this:
import Magneto from "js-magento-client";
const { MagentoAccountApi } = Magneto;
Which is not correct, but is in the process of being fixed apparently.
From the NodeJS v10 docs:
When loaded via import these modules will provide a single default
export representing the value of module.exports at the time they
finished evaluating.
import fs from 'fs';
fs.readFile('./foo.txt', (err, body) => {
if (err) {
console.error(err);
} else {
console.log(body);
}
});
All the comments above telling you that it's a bad idea to start out with an experimental feature are 100% on-point. The above is a good example. At some point this is going to change and you'll have to change your code. If you used Babel instead, you wouldn't have this issue.

Resources