jateen
jateen

Reputation: 804

Import ES Module

I am trying to create a standalone node.js project. The steps I followed are -

  1. Created a new directory and initialised it with npm init.
  2. Installed the new module for node-fetch.
  3. 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.

Upvotes: 0

Views: 525

Answers (1)

MrCodingB
MrCodingB

Reputation: 2314

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');

Upvotes: 1

Related Questions