DEV Community

Cover image for How to use require() in ECMAScript modules
Eranda K.
Eranda K.

Posted on

How to use require() in ECMAScript modules

ECMAScript modules are now becoming the new way of import/exporting modules in NodeJS ecosystem. This allows you to import and export modules using import statements rather than using require

Example 01

//multiple.js
const multiple = (num1, num2) => {
  return num1 * num2;
};
Enter fullscreen mode Exit fullscreen mode

This can be imported as

import { multiple } from "./multiple.js";

console.log(multiple(10, 50));
Enter fullscreen mode Exit fullscreen mode

Example 02 (Default Export)

Also ECMAScript modules introduces default exports which can be used as

//multiple.js
const multiple = (num1, num2) => {
    return num1 * num2;
};

export default multiple;
Enter fullscreen mode Exit fullscreen mode

Can be imported as

import multiple from "./multiple.js";

console.log(multiple(10, 50));
Enter fullscreen mode Exit fullscreen mode

We can't use ECMAScript modules in a NodeJS app by default. To do this there are two ways.

  1. You need to change the file extension of the files from *.js to *.ejs
    Module JS

  2. You can add "type": "module" in your package.json file

{
  "name": "ECMAScript-modules",
  "version": "1.0.0",
  "description": "",
  "type": "module", 
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}
Enter fullscreen mode Exit fullscreen mode

Most of the modules in NodeJS now supports ECMAScript module imports. But there may be some occasions that we still want to use require.

πŸ”΄If you use require in ECMAScript module. it will throw an error.

import crypto from 'crypto'
const fs = require('fs')
Enter fullscreen mode Exit fullscreen mode

Above code will throw following error.

require is not defined in ES module scope, you can use import instead.
Enter fullscreen mode Exit fullscreen mode

Solution πŸŽ‰

you can use createRequire to overcome this issue. Following is a sample code how to use it.

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

import crypto from 'crypto'
const fs = require('fs')
Enter fullscreen mode Exit fullscreen mode

You can also define this in a separate file and reuse it afterwards.

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

export default require;
Enter fullscreen mode Exit fullscreen mode

Then this can be used as

import require from "./cjs-require.";
const crypto = require("crypto");
Enter fullscreen mode Exit fullscreen mode

Hope you've enjoyed reading.

Please comment if you face any problems. I'm happy to help. Also connect with me on twitter

Oldest comments (1)

Collapse
 
sixman9 profile image
Richard Joseph

For me at least, this is an amazing find, specifically the createRequire( ) call.

Life safer, thank you πŸ™πŸΎ