Trying to migrate some old TypeScript code from CRA to Vite, and getting stuck on a problem with Vitest. The project has dependencies like this:
my-project (ESM)
depends on: lib1 (CJS)
depends on: lib2 (ESM)
The code seems fine at first glance, with lib1
doing something seemingly innocuous like this in TypeScript:
import * as lib2 from 'lib2'
Which transpiles to...
const lib2_1 = require('lib2');
Since lib2
is ESM, that, in principle, explains why Vitest errors out with:
Error: require() of ES Module /path/to/lib2/dist/esm/index.js from /path/to/lib1/dist/whatever.js not supported.
Instead change the require of index.js in /path/to/lib1/dist/whatever.js to a dynamic import() which is available in all CommonJS modules.
HOWEVER, this surfaces only now, because both Vite and Webpack before it would simply do the right thing, as bundlers do, since of course require()
doesn't even exist in the browser. Jest needed a little help, configuring transformIgnorePatterns
to exclude lib2
(i.e., allow transpiling lib2
to CJS, which, for all its ugliness, allows everything to function).
Now, dynamic import()
would break non-async
callers, so eventually I'd like to migrate everything to ESM, but that will have to be a future endeavor. Meanwhile, I should be able to get Vite and Vitest to work with the code as is... right?
For reference, my vite.config.cjs
, reduced to demonstrate the problem, is pretty simple:
const { defineConfig } = require('vitest/config');
const react = require('@vitejs/plugin-react').default;
module.exports = defineConfig({
plugins: [react()],
server: { /* ... */ },
test: {
environment: 'happy-dom',
globals: true,
},
});
So, the question is: Since Vite is doing what's needed out-of-the-box to support require
of ESM, how do I configure Vitest to follow suit?