CommonJs Modules - What we know as the
require()method for importing modules and
module.exportsfor exporting. This is designed for synchronous loading and mainly used for server.
Asynchronous Module Definition (AMD) - The most popular implementation of this standard is RequireJS ↗️. This is designed for asynchronous loading and mainly used for browsers.
The goal for ECMAScript 6 modules was to create a format that both users of CommonJS and of AMD are happy with. The syntax for importing modules looks like this..
and exporting with named and default exports like this..
If you try to run this code directly then you would get an error something like
Now, if you are using Node.js version 14.x.x or above then the simplest fix is to add “type”: “module” in your package.json file.
However if you are on any version below 14, you would have to use Babel to compile your code before running it.
Let’s start by installing some dev dependencies,
Next is to create a
babel.config.json file and add the following config,
Now you just have to use
babel-node instead of node, so your start/dev script may look like this now
Hope this was helpful. See you in another one 👋