Node: ReferenceError: require is not defined

Created on 5 Jun 2020  Â·  14Comments  Â·  Source: nodejs/node

  • Version:v12.18.0
  • Platform:Linux dev 5.3.0-53-generic #47~18.04.1-Ubuntu SMP Thu May 7 13:10:50 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
  • Subsystem:require

What steps will reproduce the bug?

  1. Download LTS 12.18.0 from https://nodejs.org/dist/v12.18.0/node-v12.18.0-linux-x64.tar.xz
  2. Untar compressed file
  3. Save a js file with the following code: (Let's called it test.js)
    console.log(require)
  4. Run //node-v12.18.0-linux-x64/bin/node test.js
  5. Node returns error output stating that require is not defined.

How often does it reproduce? Is there a required condition?

All the time.

What is the expected behavior?

The behavior should be similar to node executing the same one liner in REFL interactive shell.

$ node
Welcome to Node.js v12.18.0.
Type ".help" for more information.
> console.log(require)
[Function: require] {
  resolve: [Function: resolve] { paths: [Function: paths] },
  main: undefined,
  extensions: [Object: null prototype] {
    '.js': [Function],
    '.json': [Function],
    '.node': [Function]
  },
  cache: [Object: null prototype] {}
}

What do you see instead?

$ node test.js
(node:13608) ExperimentalWarning: The ESM module loader is experimental. file:///somedirectory/test.js:1 console.log(require); ^ ReferenceError: require is not defined

Additional information


The issue does not happen in older node versions. See text output below

$ node --version
v8.10.0
$ node test.js
{ [Function: require]
  resolve: { [Function: resolve] paths: [Function: paths] },
  main:
   Module {
     id: '.',
     exports: {},
     parent: null,
     filename: '/somedirectory/test.js',
     loaded: false,
     children: [],
     paths:
      [ '/somedirectory/node_modules',
      ...,
      ...,
        '/node_modules' ] },
  extensions: { '.js': [Function], '.json': [Function], '.node': [Function] },
  cache:
   { '/somedirectory/test.js':
      Module {
        id: '.',
        exports: {},
        parent: null,
        filename: '/somedirectory/test.js',
        loaded: false,
        children: [],
        paths: [Array] } } }

Most helpful comment

We could perhaps expand the error message to include something like “file.js is loaded as an ES module due to /path/to/package.json containing "type": "module"”

All 14 comments

cc @nodejs/modules-active-members

Hey thank you for the report and engaging, this is actually intentional. You cannot require from an ESM module - you need to use createRequire :]

import { createRequire } from 'module';
const require = createRequire(import.meta.url);
// can now use `require` in an ESM

See this section in the docs regarding why and how to work around it.

(I'm closing since I don't think this is a bug - as usual, if anyone feels strongly feel free to reopen)

Can you verify that this happens in any directory? By default a .js file shouldn’t be treated as a module. I suspect that you may be in a directory (or nested directory below) where a package.json has a “type” field set to “module”.

BTW: Apologies, I somehow missed that OP did not realize they were running inside module context 🙏 Thanks for the comment Jan.

Let's reopen for now.

@jkrems You are right. The module "type" was causing the issue. Thank you for flagging that out.

We could perhaps expand the error message to include something like “file.js is loaded as an ES module due to /path/to/package.json containing "type": "module"”

We could perhaps expand the error message to include something like “file.js is loaded as an ES module due to /path/to/package.json containing "type": "module"”

Yes. That will be very helpful!

Let's reopen it the meantime for the error message improvement.

I could work on this

Thanks for this thread, was facing the same issue. More precise error message would definitely help people.

Hey thank you for the report and engaging, this is actually intentional. You cannot require from an ESM module - you need to use createRequire :]

import { createRequire } from 'module';
const require = createRequire(import.meta.url);
// can now use `require` in an ESM

See this section in the docs regarding why and how to work around it.

(I'm closing since I don't think this is a bug - as usual, if anyone feels strongly feel free to reopen)

Thanks so much, I was having this issue using a type:module in package.json but now it's working thanks to your solution.

ReferenceError: createRequire is not defined

@priya-concetto did you import it from "module" ?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Icemic picture Icemic  Â·  3Comments

addaleax picture addaleax  Â·  3Comments

Brekmister picture Brekmister  Â·  3Comments

fanjunzhi picture fanjunzhi  Â·  3Comments

cong88 picture cong88  Â·  3Comments