英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论