Import ES Module - node.js

I am trying to create a standalone node.js project. The steps I followed are -
Created a new directory and initialised it with npm init.
Installed the new module for node-fetch.
Trying to import the fetch module using const fetch = require("node-fetch"); statement.
Getting the following error -
const fetch = require("node-fetch");
Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/jatin/Desktop/test-app/node_modules/node-fetch/src/index.js from /Users/jatin/Desktop/test-app/index.js not supported. Instead change the require of /Users/jatin/Desktop/test-app/node_modules/node-fetch/src/index.js in /Users/jatin/Desktop/test-app/index.js to a dynamic import() which is available in all CommonJS modules. at Object.<anonymous> (/Users/jatin/Desktop/test-app/index.js:2:15) { code: 'ERR_REQUIRE_ESM' }
The node version I have on my machine is - v16.9.0.

You should use an ES module import instead of require.
import * as fetch from 'node-fetch';
You could also use a dynamic import, as the error message states.
const fetch = import('node-fetch');

Related

Getting error while using node js "chalk" module

I want to use node js chalk module but I am getting the following error
let chalk = require('chalk');
^
Error [ERR_REQUIRE_ESM]: require() of ES Module F:\Bhaskar\Learning\CompleteWebDevelopmentCourse\node_modules\chalk\source\index.js from F:\Bhaskar\Learning\CompleteWebDevelopmentCourse\NodeJs\npm.js not supported.
Instead change the require of index.js in F:\Bhaskar\Learning\CompleteWebDevelopmentCourse\NodeJs\npm.js to a dynamic import() which is available in all CommonJS modules.
at Object.<anonymous> (F:\Bhaskar\Learning\CompleteWebDevelopmentCourse\NodeJs\npm.js:1:13) {
code: 'ERR_REQUIRE_ESM'
}

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

Node.js - An error occurred during import third party library

Guys I am still new to Node.js and facing a problem during importing a third-party module. The module name is #azure/storage-blob and my package.json file is using "type": "module" setting.
When I try to import this module with the following syntax. I am getting an error.
import { BlobServiceClient } from "#azure/storage-blob";
SyntaxError: The requested module '#azure/storage-blob' does not provide an export named 'BlobServiceClient'
at ModuleJob._instantiate (internal/modules/esm/module_job.js:92:21)
at async ModuleJob.run (internal/modules/esm/module_job.js:107:20)
at async Loader.import (internal/modules/esm/loader.js:179:24)
But with this setting, this project is working fine on my other machine and I still don't understand it.
When I use this syntax instead of directly import the error goes away.
import AzureStorageBlob from "#azure/storage-blob";
const { BlobServiceClient } = AzureStorageBlob;
Could you please help me to understand this issue?

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

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.

how to use node module with es6 import syntax in typescript

I have a typescript project which has uses one of our node modules which normally runs in our front-end. We are now looking to use this module in node on our server.
The module uses es6 import syntax import { props } from 'module/file'
When I include a ref in typescript using either of the following methods
import { props } from 'module/file';
var props = require('module/file');
I get the following error from typescript
unexpected token 'import'
(function (exports, require, module, __filename, __dirname) { import
It's a big job to re-write the module, and I've tried using babel with babel-plugin-dynamic-import-node, as well as SystemJS.
The problem with these systems is that they are all asynchronous, so I can't import the module in the standard fashion, so I would need to do a whole bunch of re-write when we get to the point that I can use import natively in node.js.
I can't be the first person to have this issue, but I can't seem to find a working solution.
--------------- update with set-up -------------
In response to #DanielKhoroshko's response. The original module I am trying to import is normally packaged by webpack in order to use on the front-end. I am now trying to use this same module both server-side and in the front-end (via webpack on the front-end) without re-writing the imports to use require and without running webpack to bundle the js to use on the server.
To be clear, the original module is written in JS, our service which is trying to use this module is written in typescript and transpiled. When the typescript tries to require the old module which uses import, it is at this point that we are running into the issue.
------------------ some progress ---------------------------
I've made some progress by creating a file in my imported module which uses babel in node.js to transpile the es6 code into commonJS modules.
I've done this via
var babel = require("babel-core")
var store = babel.transformFileSync(__dirname + '/store.js', {
plugins: ["transform-es2015-modules-commonjs"]
});
module.exports = {
store: store.code
}
I can now get the store in my new node.js project. However, the submodules within the store.js file are not included in the export.
So where in my module, it says
import activities from './reducers/activities';
I now get an error
Cannot find module './reducers/activities'
How can I get babel to do a deep traversal to include the sub-directories?
unexpected token 'import' means you are running es-modules code in environment that doesn't support import/export commands. If you are writing you code in TypeScript it's important to transpile it first before building for the browser or use ts-node to run it server-side.
If you are using webpack there are loaders ts-loader and awesome-typescript-loader
What is your setup?
To describe the module you would need to create an activities.d.ts file in the same folder where the js-version (I understood it is called activities.js and containers a reducer) resides with the following (approx.):
import { Reducer } from 'redux';
export const activities: Reducer<any>;
#Daniel Khoroshko was right in many ways, I ended up finding #std/esm which lets you import es6 modules and worked find for fetching the included imports as well.
var babel = require('babel-register')({
presets: ["env"]
});
require = require('#std/esm')(module);
var store = require('ayvri-viewer/src/store');
exports.default = {
store: store
}
I had to run babel to get a consistent build from es6 to node compatible es5

Resources