MSW(模拟服务工作者)+ Vite:未捕获的引用错误:require未定义

huangapple go评论53阅读模式
英文:

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

问题

我正在按照官方文档的步骤安装服务:https://mswjs.io/docs/getting-started/install

这段代码:

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

Uncaught ReferenceError: require is not defined

我已经使用 Vite 设置了项目。解决这个问题的正确方法是什么。

英文:

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.

答案1

得分: 8

Vite不使用require,请尝试使用import代替:

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

来源(尽管是另一个问题,但在这里同样适用):https://github.com/vitejs/vite/issues/3409#issuecomment-841049875

英文:

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

huangapple
  • 本文由 发表于 2023年2月27日 06:02:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75575267.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定