DEV Community

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

Posted on • Updated on

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

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
Enter fullscreen mode Exit fullscreen mode
console.log("Hello, JavaScript Modules!");
Enter fullscreen mode Exit fullscreen mode
$ node --version
v14.0.0
$ node ./main.mjs
Hello, JavaScript Modules!
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode
$ touch math.mjs
Enter fullscreen mode Exit fullscreen mode
export const add = (a, b) => a + b;
Enter fullscreen mode Exit fullscreen mode
$ node ./main.mjs
Hello, JavaScript Modules!
3
Enter fullscreen mode Exit fullscreen mode

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());
Enter fullscreen mode Exit fullscreen mode
$ node ./main.mjs
Hello, JavaScript Modules!
3
x64
Enter fullscreen mode Exit fullscreen mode

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.

Oldest comments (0)