javascriptvitemsw

MSW (Mock Service Worker) + Vite: Uncaught ReferenceError: require is not defined


I'm installing the service following the steps at the official docs: https://mswjs.io/docs/getting-started/install

This piece of code:

if (process.env.NODE_ENV === 'development') {
  const { worker } = require('../tests/mocks/browser');
  worker.start();
}

Uncaught ReferenceError: require is not defined

I've setup the project using Vite. What's the correct approach to solving this.


Solution

  • Vite does not use require, try to use import instead:

    if (process.env.NODE_ENV === 'development') {
      const { worker } = await import('../tests/mocks/browser');
      worker.start();
    }
    

    Source (albeit another issue, but works here as well): https://github.com/vitejs/vite/issues/3409#issuecomment-841049875