Node.js projects can choose whether .js files load as CommonJS or ECMAScript modules. Enabling ES modules at the package level lets source files use import and export syntax without renaming every file to .mjs.

The nearest parent package.json controls how Node.js interprets .js files inside a package. A top-level "type": "module" field makes entry points and imported .js files use the ES module loader, while .cjs remains available for any file that still needs CommonJS.

Use this package-level setting when the project is meant to run mostly as ES modules. Recent Node.js releases can inspect a .js file without an explicit module marker, but an explicit package type keeps the runtime, test tools, bundlers, and editors aligned before code is executed.

Steps to enable ES modules in Node.js:

  1. Open the Node.js project root that contains package.json.

    If the project does not have package.json yet, initialize package metadata first.
    Related: How to create a Node.js project with npm

  2. Back up the current package metadata.
    $ cp package.json package.json.bak

    Setting type to module changes how Node.js loads every .js file under this package unless a deeper package.json overrides it. Rename files that must stay CommonJS to .cjs before running them.

  3. Set the package type to ES module.
    $ npm pkg set type=module
  4. Confirm the saved package type.
    $ npm pkg get type
    "module"
  5. Create a temporary export file named esm-value.js.
    export const moduleMode = 'ES module';
  6. Create a temporary entry file named esm-check.js.
    import { moduleMode } from './esm-value.js';
     
    console.log('Loaded as ' + moduleMode);
  7. Run the ES module smoke test.
    $ node esm-check.js
    Loaded as ES module

    If Node.js reports that import cannot be used outside a module, run the command from the project root and check for a nearer package.json without "type": "module".

  8. Remove the temporary smoke-test files.
    $ rm esm-check.js esm-value.js

    Keep package.json.bak or a version-control diff until the real project entry point and tests run with the new module type.