NodeJS (Server): ReferenceError: require is not defined when type: module

Viewed 11815

On Node 13.8 I'm trying to use import / export.

EG: import {ChatClient, Message, MessageParser} from './chat-client/module.js';

But when i do this, I get

SyntaxError: Cannot use import statement outside a module

So in my package.json I set "type" : "module" but now when I try to use const io = require('socket.io-client');

I get ReferenceError: require is not defined

Is there a way to use import / export AND require?

The original error, does that just mean I have to wrap my library in a NPM library? It's a Library that's used both front end and backend so using import / export is important.

Thanks

4 Answers

ES Modules in Node >= 14 do not support require.

However if you want to add it, u have to add this at the top of your file: Everything should work fine.

import { createRequire } from 'module';
const require = createRequire(import.meta.url);

Several points:

  1. Use .mjs instead of .js.
  2. Never use require.
  3. It is optional to use "type": "module".

If you use {"type":"module"} you won't be able to use require function in your project. So if you want to use require as well import you need to add the following properties in package.json.

  "babel": {
    "presets": [
      "stage-3",
      "latest"
    ]
  }

"babel-preset-latest": "^6.16.0"
"babel-preset-stage-3": "^6.5.0"
Related