Skip to content

Instantly share code, notes, and snippets.

@martinadamsdev
Forked from Jaid/migratingRules.md
Created September 24, 2021 02:13
Show Gist options
  • Save martinadamsdev/5ac2bd9f10760450fcb8c319d553e505 to your computer and use it in GitHub Desktop.
Save martinadamsdev/5ac2bd9f10760450fcb8c319d553e505 to your computer and use it in GitHub Desktop.
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

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