viteckeditor5

CKEditor 5 and Vite 5: TypeError: __require.resolve is not a function


I'm trying to upgrade from Vite 4 to Vite 5.

After updating to Vite 5, I got the following warning:

The CJS build of Vite's Node API is deprecated. See https://vitejs.dev/guide/troubleshooting.html#vite-cjs-node-api-deprecated for more details.

So I edited package.json and added "type": "module",.

Then I tried to build the app again and got the following error:

 ERROR  failed to load config from /Users/private/d/ionic/vite.config.ts                                                                                                   21:33:20


 ERROR  error during build:                                                                                                                                                21:33:20
TypeError: __require.resolve is not a function
    at vite_config_default (file:///Users/private/d/ionic/vite.config.ts.timestamp-1700829200243-c26807f7c170c.mjs:80:36)
    at loadConfigFromFile (file:///Users/private/d/ionic/node_modules/vite/dist/node/chunks/dep-ErEj4WmL.js:66149:15)
    at async resolveConfig (file:///Users/private/d/ionic/node_modules/vite/dist/node/chunks/dep-ErEj4WmL.js:65750:28)
    at async build (file:///Users/private/d/ionic/node_modules/vite/dist/node/chunks/dep-ErEj4WmL.js:64922:20)
    at async CAC.<anonymous> (file:///Users/private/d/ionic/node_modules/vite/dist/node/cli.js:845:9)

This is caused by the way I am importing the CKEditor 5 plugin. I know this because when I remove the CKEditor 5 plugin from my vite.config.ts, the error does not appear. (Of course, in that case, the app doesn't work, because CKEditor doesn't get imported properly.)

I think this is because CKEditor is using CJS, but Vite is now defaulting to ESM. There is work underway to have CKEditor default to ESM, but the PRs have not been committed yet. So how do I use CKEditor with Vite 5 in ESM mode today?


Solution

  • Make sure to not use require.resolve directly, but use the createRequire( import.meta.url ) method as shown in the CKeditor documentation: https://ckeditor.com/docs/ckeditor5/latest/installation/advanced/alternative-setups/integrating-from-source-vite.html#vite-configuration