Require with Import - NodeJS

You can use require and import together with:

Method 1

First rename file to .mjs or add "type":"module" to your package.json file.

// create require function in the mjs
import { createRequire } from "module";
const require = createRequire(import.meta.url);

Method 2

Files

package.json

{
  "main": "esm_main.js",
  "module": "esm_index.js",
  "dependencies": {
    "esm": "^3.2.25"
  },
  "esm": {
    "cjs": true,
    "mode": "auto",
    "mainFields": ["modules", "main"]
  }
}

esm_main.js

require = require("esm")(module);
module.exports = require("./esm_index.js");

esm_index.js

// Import statement
import { hostname } from "os";

// and require
const os = require("os");

console.log(hostname());

console.log(os.arch());

test

nexss esm_main.js

# OR just

node esm_main.js
If you found it valuable, please join to the nexss.com supporters at: Support Nexss.com