Skip to content

Instantly share code, notes, and snippets.

@Jaid
Last active January 15, 2023 15:12
Embed
What would you like to do?
ESLint rules for migrating projects from CommonJS to ESM

ESLint rules

The ESM standard is considered stable in NodeJS and well supported by a lot of modern JavaScript tools.

ESLint does a good job validating and fixing ESM code (as long as you don't use top-level await, coming in ESLint v8). Make sure to enable the latest ECMA features in the ESLint config.

  • .eslint.json
{
  "env": {
    "es2021": true,
    "node": true
  },
  "parserOptions": {
    "sourceType": "module"
  }
}

Rules that can be helpful for anyone who wants to migrate a project from CommonJS to ESM now:

eslint-plugin-node

ESLint Plugin Rule Source Description Fixable
node no-missing-import πŸ”— disallow import declarations which import non-existence modules -
node no-extraneous-import πŸ”— disallow import declarations which import extraneous modules -
node no-sync πŸ”— disallow synchronous methods -
node file-extension-in-import πŸ”— enforce the style of file extensions in import declarations Yes

eslint-plugin-import

ESLint Plugin Rule Source Description Fixable
import extensions πŸ”— Ensure consistent use of file extension within the import path. -
import no-unresolved πŸ”— Ensure imports point to a file/module that can be resolved. -
import no-useless-path-segments πŸ”— Prevent unnecessary path segments in import and require statements. Yes
import no-extraneous-dependencies πŸ”— Forbid the use of extraneous packages. -
import no-commonjs πŸ”— Report CommonJS require calls and module.exports or exports.*. -

eslint-plugin-unicorn

ESLint Plugin Rule Source Description Fixable
unicorn prefer-module πŸ”— Prefer JavaScript modules (ESM) over CommonJS. Yes
unicorn prefer-node-protocol πŸ”— Prefer using the node: protocol when importing Node.js builtin modules. Yes
unicorn prefer-top-level-await πŸ”— Prefer top-level await over top-level promises and async function calls. Suggest

Read more

@mohanraj-r
Copy link

Thank you very much for this very useful info! πŸ‘

@azu
Copy link

azu commented Jan 15, 2023

It is very helpful πŸ‘

I've created a wrapper CLI of ESLint + rules.
This tool has built-in rules which are based on this article.

npx eslint-cjs-to-esm "./src/**/*.{js,ts}" --fix

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment