Announcing core Node.js support for ECMAScript modules

  • Files ending in .mjs.
  • Files ending in .js, or extensionless files, when the nearest parent package.json file contains a top-level field “type” with a value of “module”.
  • Strings passed in as an argument to —-eval or piped to node via STDIN, with the flag —-input-type=module.
  • Files ending in .cjs.
  • Files ending in .js, or extensionless files, when the nearest parent package.json file contains a top-level field “type” with a value of “commonjs”.
  • Strings passed in as an argument to --eval or piped to node via STDIN, with the flag --input-type=commonjs.
  • Relative URLs (‘./file.mjs’)
  • Absolute file:// URLs (‘file:///opt/app/file.mjs’)
  • Package names (‘es-module-package’)
  • Paths within packages (‘es-module-package/lib/file.mjs’)

Common Gotchas

Mandatory file extensions
A file extension must be provided when using the import keyword. Directory indexes (e.g. ‘./startup/index.js’) must also be fully specified.

Writing packages

At the moment, we recommend that packages are written using either entirely CommonJS or entirely ES module syntax for the JavaScript sources intended for Node.js. The modules team is working on better support for “dual” packages, that provide CommonJS sources for package consumers using require and ES module sources for package consumers using import. The current experimental feature covering this use case is conditional exports, and the team hopes to ship that or an alternative by the end of January 2020 if not earlier. See recommended patterns in Dual CommonJS/ES Module Packages.

Works in progress

  • Loaders. Work is ongoing for an API to allow for custom loaders that can support use cases like runtime transpilation, rewriting specifiers (package or file paths) and code instrumentation. The —-experimental-loader API will still change considerably before this is unflagged.
  • Dual CommonJS/ES module packages. We want to provide a standard way for package authors to publish a package that can be both required into CommonJS or imported into an ES module. See Dual CommonJS/ES Module Packages. The plan is for this to be finalized by the end of January 2020 if not earlier.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Node.js

Node.js

Node.js is a collaborative open source project dedicated to building and supporting the Node.js platform. https://nodejs.org/en/