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;
};
This can be imported as
import { multiple } from "./multiple.js";
console.log(multiple(10, 50));
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;
Can be imported as
import multiple from "./multiple.js";
console.log(multiple(10, 50));
We can't use ECMAScript modules in a NodeJS app by default. To do this there are two ways.
You need to change the file extension of the files from
*.js
to*.ejs
You can add
"type": "module"
in yourpackage.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"
}
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')
Above code will throw following error.
require is not defined in ES module scope, you can use import instead.
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')
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;
Then this can be used as
import require from "./cjs-require.";
const crypto = require("crypto");
Hope you've enjoyed reading.
Please comment if you face any problems. I'm happy to help. Also connect with me on twitter
Top comments (3)
Aren't you forgetting the export before the line in example 01?
Like
For me at least, this is an amazing find, specifically the
createRequire( )
call.Life safer, thank you 🙏🏾
lol, now it module is not defined n es module scope