As more and more developers are adapting the new ECMAScript6 standards, you may want to use the similar syntax in your application. Node JS, by default do not support ES modules, so we may have to take a couple of easy to do extra steps to work with them.

Suppose you have a file named mymodule.js with the following code

Copy to Clipboard

and you want to import it in another file main.js like this

Copy to Clipboard

Now, if you run the application with ‘node main’ command, node js may throw and error like this

“Warning: To load an ES module, set “type”: “module” in the package.json or use the .mjs extension.”

Way 1

As the error suggests, we need to rename the filename from ‘js’ to ‘mjs’

If you rename only ‘main.js’ to ‘main.mjs’, then node js will throw an error similar to this

“The requested module ‘./mymodule.js’ is a CommonJS module, which may not support all module.exports as named exports. CommonJS modules can always be imported via the default export,”

With that error we can understand that, now in our application, ‘main.mjs’ is using ES module and ‘mymodule.js’ is using CommonJS modules which are two different module systems. To bring all files under ES module system, we need to rename ‘mymodule.js’ also to ‘mymodule.mjs’.

Way 2:

Alternatively, instead of renaming all files to ‘.mjs’ extension, we can simply add a new entry to our ‘package.json’ file. If you do not have this file, you can simply create one manually or by using ‘npm init’ command. The ‘npm init’ prompts for different entries which you can enter or leave them blank.

For this example purpose, we gave blank to all options except changing main file name from ‘index.js’ to ‘main.js’.

Now we need to add one new entry “type” to the json file with the value “modules”

Copy to Clipboard

With this file in place, we can now rename the files from ‘mjs’ to ‘js’.