DEV Community

loading...
Cover image for Import/Export in Node.js without any third-party libraries

Import/Export in Node.js without any third-party libraries

aminnairi profile image Amin Updated on ・2 min read

Since Node.js 14, we can now enjoy using JavaScript Modules in our scripts.

If you don't know what a JavaScript Module is, I suggest you go and read this article from Mozilla Developer Network before continuing here.

$ touch main.mjs
console.log("Hello, JavaScript Modules!");
$ node --version
v14.0.0
$ node ./main.mjs
Hello, JavaScript Modules!

The only catch here is that you now write modules with a .mjs extension, instead of the usual .js one.

Note: you probably used the --experimental-modules with previous releases of Node.js, you can now safely remove this flag if you just updated your version of Node.js to version 14.

This means you can import other modules as well of course.

import {add} from "./math.mjs";

console.log("Hello, JavaScript Modules!");
console.log(add(1, 2));
$ touch math.mjs
export const add = (a, b) => a + b;
$ node ./main.mjs
Hello, JavaScript Modules!
3

What is slightly different from the official JavaScript Module standard and Node.js, is that you can still use the Node.js Module Resolution to import modules from the standard library, or from the node_modules folder.

import {add} from "./math.mjs";
import {arch} from "os";

console.log("Hello, JavaScript Modules!");
console.log(add(1, 2));
console.log(arch());
$ node ./main.mjs
Hello, JavaScript Modules!
3
x64

You can now ditch Babel (unless you need to use non-standard or staged features) if you used JavaScript Modules with Node.js since there is no need for any transpilation now.

Want to learn more? You can read the ECMAScript Modules documentation from the official Node.js website here.

Discussion (0)

pic
Editor guide