others-how to solve `ReferenceError: require is not defined in ES module scope, you can use import instead` error when trying to run a node.js application?

1. Problem

➜  simple_websocket_server git:(master) ✗ node app.js 0.0.0.0 18081 myserver1
file:///Users/bswen/lua-projects/kong-plugin/server/simple_websocket_server/app.js:2
const process=require("process");
              ^

ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and '/Users/bswen/lua-projects/kong-plugin/server/simple_websocket_server/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
    at file:///Users/bswen/lua-projects/kong-plugin/server/simple_websocket_server/app.js:2:15
    at ModuleJob.run (node:internal/modules/esm/module_job:185:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:281:24)
    at async loadESM (node:internal/process/esm_loader:88:5)
    at async handleMainPromise (node:internal/modules/run_main:65:12)
➜  simple_websocket_server git:(master) ✗ 

The core error message is as follows:

ReferenceError: require is not defined in ES module scope, you can use import instead

The code that caused the above error is as follows:

code:

import { WebSocketServer } from 'ws';
const process=require("process");
const args = process.argv.slice(2);

var appIp = '0.0.0.0';
var port = 18080;
var appName = 'myserver';

console.log("SimpleWebSocketServer Usage: node app.js <listen-ip> <listen-port> <server-name>");
console.log("For example: node app.js 127.0.0.1 8080 myserver");

if(args.length>=1) {
    appIp=args[0];
}
if(args.length>=2) {
    var appport = args[1];
    console.log('appport=',appport)
    port = parseInt(appport);
    if(Number.isNaN(port)) {
        port = defaultPort;
    }
}
if(args.length>=3) {
    appName = args[2];
}


const wss = new WebSocketServer({ host: appIp,port: 18080 },function () {
    console.log('SimpleWebSocketServer started, listening to port '+port+' on '+appIp+",name:"+appName);
});

wss.on('connection', function connection(ws) {
    ws.on('message', function message(data) {
        console.log(appName,' received: %s', data);
    });

    ws.send('Connected,wait for your messages...');
});

package.json

{
  "name": "simple_websocket_server",
  "version": "1.0.0",
  "description": "",
  "type": "module",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "npm-pack-all": "^1.12.7",
    "ws": "^8.6.0"
  }
}



2. Solution

change from

const process=require("process");

to this:

import process from 'process';

Because: The import command of ES6 modules can load CommonJS modules, but only as a whole, not just a single output item.

// Correct
import packageMain from 'commonjs-package';
// Wrong
import { method } from 'commonjs-package';

This is because ES6 modules need to support static code analysis, and the output interface of CommonJS modules is module.exports, which is an object and cannot be statically analyzed, so it can only be loaded as a whole.

Loading a single output item can be written as follows.

import packageMain from 'commonjs-package';
const { method } = packageMain;



3. Summary

In this post, I demonstrated how to solve the ReferenceError: require is not defined in ES module scope, you can use import instead error when try to import a package in node.js. That’s it, thanks for your reading.