引入vite-plugin-mock启动报错

错误信息

file:///D:/code/back-stage/node_modules/vite-plugin-mock/dist/index.mjs:128 
if (!require.cache) { 

^ ReferenceError: require is not defined 
  at cleanRequireCache (file:///D:/code/back-stage/node_modules/vite-plugin-mock/dist/index.mjs:128:3) 
  at getMockConfig (file:///D:/code/back-stage/node_modules/vite-plugin-mock/dist/index.mjs:157:3) 
  at createMockServer (file:///D:/code/back-stage/node_modules/vite-plugin-mock/dist/index.mjs:52:20) 
  at configResolved (file:///D:/code/back-stage/node_modules/vite-plugin-mock/dist/index.mjs:246:16) 
  at file:///D:/code/back-stage/node_modules/vite/dist/node/chunks/dep-4RECYSE1.js:67205:24 at Array.map (<anonymous>) 
  at resolveConfig (file:///D:/code/back-stage/node_modules/vite/dist/node/chunks/dep-4RECYSE1.js:67205:10) 
  at async _createServer (file:///D:/code/back-stage/node_modules/vite/dist/node/chunks/dep-4RECYSE1.js:59489:20) 
  at async CAC.<anonymous> (file:///D:/code/back-stage/node_modules/vite/dist/node/cli.js:764:24) 
  Node.js v20.10.0 error Command failed with exit code 1. info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

解决办法

方法一:

这个问题是vite-plugin-mock@3.0.0版本出现的,可以选择降低版本

yarn remove vite-plugin-mock
yarn add vite-plugin-mock@2.9.1 -D

降低版本后就没有上面哪个报错了。

方法二:

网上很多解决办法是修改node_modules/vite-plugin-mock/dist/index.mjs文件,但是这种方式有问题,就是可能文件会还原,又要重新修改,而且是直接修改源码。总觉得不好,这里还是给出这种解决方法,给有需要的人。

node_modules/vite-plugin-mock/dist/index.mjs的文件中加入下面两行代码

import { createRequire } from 'node:module';
const require=createRequire(import.meta.url);

引入vite-plugin-mock启动报错
https://www.zhaojun.inkhttps://www.zhaojun.ink/archives/import-vite-plugin-mock-error
作者
卑微幻想家
发布于
2023-12-05
许可协议