ECMAScript Modules are the new default code reuse standard

ECMAScript modules are the official standard format to package JavaScript code for reuse in the future. ES6 modules now have full support in Node.js 12 and above!

If you’ve used TypeScript in the past few years, you will be familiar with the module import syntax in your application. Instead of the require("module"), most TypeScript applications use some variation of import module from "module".

TypeScript will then transpile this syntax into CommonJS require statements for you.

If you use TypeScript, you can just change your tsconfig settings to output ECMAScript 6 (ES6) modules and you will be good to go. If you don’t use TypeScript, you might have to do some rewriting to get your app updated.

Here are the solutions to these issues. It took me a bit of time and investigation to figure out these solutions when I was upgrading an application to use ECMAScript modules like configuring TypeScript, setting up Jest, configuring the package.json correctly, and more.

Node.js support for ECMAScript 6 (ES6) modules

The support for ECMAScript modules is stable as of Node.js 14. So, there are no issues using this functionality.

If you still use Node.js 12 in production (I’m guilty of this!), then the ECMAScript modules feature is marked as ‘Experimental’ so you should use some caution. But the support is fully there. Please note that Node.js 12 is at its end-of-life for support from 2022/04/30. Therefore, you should be considering upgrading to Node.js 14 anyway.

If you provide a library that other applications depend on, of course, it is worth being mindful of the Node.js versions your customers are supporting.

In general, most actively developed Node.js apps as of 2021 should support ECMAScript modules natively.

#javascript #programming #typescript #nodejs

Don’t Make These Mistakes While Converting Your Node.js App
1.05 GEEK