node.jsviterequirees6-modules

plugin externalize-deps - This package is ESM only but it was tried to load by `require`


I am installing a plugin in Vite, but I run into an error message stating that the package only supports ESM, not CJS.

package.json

{
  "devDependencies": {
    "example-package": "^1",
    "vite": "^6"
  }
}

vite.config.js

import { defineConfig } from "vite";
import examplePlugin from "example-package"; // that's ESM import, whats a problem?

export default defineConfig({
  plugins: [
    examplePlugin(),
  ],
});

✘ [ERROR] Failed to resolve "example-package". This package is ESM only but it was tried to load by require. [plugin externalize-deps]

I have installed the package correctly via npm, as the import is handled properly in the vite.config.js file. So what is the issue with ESM import?


Solution

  • It's possible that you imported the plugin into vite.config.js using ESM, but vite.config.js works as CJS by default unless instructed otherwise.

    The error mainly occurs in Node.js v22 or lower, where ESM files cannot load sources by default using require. In versions of Node.js greater than v22, this behavior can be enforced with the --experimental-require-module flag, but it is not recommended. Instead, use well-established stable and clear solutions.

    How can I tell vite.config.js that I want to run it as ESM?

    Solutions