waku: Cannot import commonjs module from server component

When trying to import a CJS module from a server component I get an error in dev & production

Error when evaluating SSR module /src/components/App.tsx: failed to import "/src/components/foo.cjs"
|- ReferenceError: require is not defined
    at eval (/Users/tom.sherman/code/waku-example/src/components/foo.cjs:3:31)
    at instantiateModule (file:///Users/tom.sherman/code/waku-example/node_modules/.pnpm/vite@4.4.7/node_modules/vite/dist/node/chunks/dep-3b8eb186.js:55920:15)

Cannot render RSC ReferenceError: require is not defined
    at eval (/Users/tom.sherman/code/waku-example/src/components/foo.cjs:3:31)
    at instantiateModule (file:///Users/tom.sherman/code/waku-example/node_modules/.pnpm/vite@4.4.7/node_modules/vite/dist/node/chunks/dep-3b8eb186.js:55920:15)

Minimal reproduction: https://github.com/tom-sherman/waku-example/commit/77cf3501920bacdd2fd9a873d01abc4e848b373f

About this issue

  • Original URL
  • State: closed
  • Created a year ago
  • Reactions: 1
  • Comments: 16 (11 by maintainers)

Most upvoted comments

Another solution is to externalize the library. I think it’s a valid workaround.

https://github.com/dai-shi/waku/blob/7398b45ed1c7858e3a24c04c35fd32efc2bc54b2/packages/website/vite.config.ts#L4-L10

Please note that this is DEV-only issue now.

@tom-sherman commonjs should work for PRD bundling.

So, this looks like vite loadSsrModule cannot handle cjs bundle.

Related issue: https://github.com/vitejs/vite/issues/3024

Another solution is to externalize the library. I think it’s a valid workaround.

https://github.com/dai-shi/waku/blob/7398b45ed1c7858e3a24c04c35fd32efc2bc54b2/packages/website/vite.config.ts#L4-L10

Please note that this is DEV-only issue now.

@tom-sherman commonjs should work for PRD bundling.

And for your anothor issue https://github.com/tom-sherman/waku-desktop/pull/2, simply add external can not resolve all the problem.

CleanShot 2023-08-04 at 17 22 08@2x

You still will get a following runtime error:

TypeError: Cannot read properties of undefined (reading 'getVersion')

This is because the whole code executes in a node environment instead of electron. So when you import you will only get the execute path of Electron just like the doc says https://github.com/electron/electron#programmatic-usage.

Maybe you should encapsulate a remote call for server and electron environment to communicate so that you can use the original electron ability.

btw, .cts nor .mts doesn’t work and we need to deal with it

Fair point, this was the easiest way to trigger the error for me but I also was able to trigger the error by importing a CJS-only package from node_modules

I think these days it’s pretty unlikely for packages to be not have any ESM support at all, but this is pretty critical for the electron use case (electron is CJS only).