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?
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?
Rename the config-file to vite.config.mjs
(or vite.config.mts
), which will enforce modular ESM execution.
vite.config.mjs (instead of vite.config.js) or vite.config.mts (instead of vite.config.ts)
import { defineConfig } from "vite";
import examplePlugin from "example-package";
export default defineConfig({
plugins: [
examplePlugin(),
],
});
or in the project's package.json
file, set the project type to module with the "type": "module"
setting, so that every JavaScript running within will execute as modular ESM.
package.json
{
"type": "module",
"devDependencies": {
"example-package": "^1",
"vite": "^6"
}
}