Vue3's Mock solves the problem of if (!require.cache) { ^ ReferenceError: require is not defined

1. Problem description:

First, the error reported is:

ReferenceError: require is not defined

Chinese is:

ReferenceError:require 未被定义

Second, the problem is described as follows:
The demois in Vue3+Vite+TSthe form of . After being pnpm install -D vite-plugin-mock mockjsinstalled mock, vite.config.tsintroduced mockand configured in , an error is reported during the execution of the project:require 未被定义

// The configuration in vite.config.tsis mock:

// 主要的代码为:import { viteMockServe } from 'vite-plugin-mock',以及 viteMockServe({ localEnabled: command === 'serve',}) 的配置;

import {
    
     UserConfigExport, ConfigEnv } from 'vite'
import {
    
     viteMockServe } from 'vite-plugin-mock'
import vue from '@vitejs/plugin-vue'
export default ({
     
      command })=> {
    
    
  return {
    
    
    plugins: [
      vue(),
      viteMockServe({
    
    
        localEnabled: command === 'serve',
      }),
    ],
  }
}

Third, the error page displays as:

Insert image description here

2. Problem analysis:

node_modules/vite-plugin-mock/dist/index.mjsIf is index.mjsmissing in require, the problem should be solved after being introduced;

3. Problem solving:

First, open the file node_modules/vite-plugin-mock/dist/index.mjsin index.mjs:

A. The added code is:

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

B. index.mjsPage display after adding code:

Insert image description here

Second, if you execute the command to run the project at this time, it will run successfully:

Insert image description here

4. Summary:

First, if there is anything wrong or inappropriate, please give me some pointers and exchanges!
Second, if you forward or quote the content of this article, please indicate the address of this blog ( 直接点击下面 url 跳转) https://blog.csdn.net/weixin_43405300 . Creation is not easy, but it must be done and cherished!
Third, if you are interested, you can pay more attention to this column (Vue (Vue2+Vue3) essential column for interviews) ( 直接点击下面 url 跳转): https://blog.csdn.net/weixin_43405300/category_11525646.html?spm=1001.2014.3001.5482

Guess you like

Origin blog.csdn.net/weixin_43405300/article/details/135116431