《Vite 基础知识》Vite 不支持 require 解决方案(三种情况/require is not defined)

前言

首先,Vite 中没有 require 相关方法,因为它默认支持 ESM 方式加载模块!

所以,我们要理清如下两个方法

方法 require()

方法 require.context()

Vite 提供解决方案,请接着往下看!

解决方案

require() 加载模块

报错 require 未定义

Uncaught (in promise) ReferenceError: require is not defined

js 复制代码
// 报错。CommonJS 方式加载
initNav() {
	const ElementResizeDetector = require('element-resize-detector');
	const erd = ElementResizeDetector();
}

解决方案

  • 使用 EMS import() 方法;
  • 注意 require()同步加载;
  • import()异步 加载,推荐使用 await 命令。当然也可以使用 then() 方法,因为其返回 Promise 对象;
js 复制代码
// 正确。方式一(推荐):ESM 方式加载,使用 await 命令
async initNav() {
	const ElementResizeDetector = await import('element-resize-detector');
	const erd = elementResizeDetectorMaker.default();
}


// 正确。方式二:ESM 方式加载,使用 then() 方法
initNav() {
	import('element-resize-detector').then(module => {
        const erd = module.default();        
    }).catch(err => {
        console.error('加载失败');
    });
}

require() 加载图片

报错 require 未定义

Possible Unhandled Promise Rejection: ReferenceError: require is not defined

vue 复制代码
<template>
	<img class="pwd-icon" :src="pwdIcon" >
</template>
<script>
export default {
	data () {
		return {
			pwdIcon2: require('../assets/images/pwd-icon.png'),
		}
	}
}
</script>

解决方案

使用 EMS import 命令;

vue 复制代码
<template>
	<img class="pwd-icon" :src="pwdIcon" >
</template>
<script>
import PwdIcon from '../assets/images/pwd-icon.png'
export default {
	data () {
		return {
			pwdIcon: PwdIcon,
		}
	}
}
</script>

require.context() 批量加载文件

报错 require 未定义

Possible Unhandled Promise Rejection: ReferenceError: require is not defined

js 复制代码
// require 是同步加载
const modulesFiles = require.context('./src/components', true, /\.vue$/);

const modules = modulesFiles.keys().reduce((modules, modulePath) => {
    const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1');
    modules[moduleName] = modulesFiles(modulePath).default;
    return modules;
}, {});

解决方案

使用 import.meta.glob ,可异步同步 加载。详见《Vite 基础知识:使用 Glob 动态加载 .vue 文件》

js 复制代码
// 异步,返回 Promise 对象
const modules = import.meta.glob('./src/components/**/*.vue');

for (const path in modules) {
    modules[path]().then((mod) => {
        console.log(path, mod.default);
    })
}

// 同步,配置参数 { eager: true }
const modules = import.meta.glob('./src/components/**/*.vue', { eager: true });

for (const path in modules) {
    console.log(path, modules[path].default);
}
相关推荐
哆啦A梦15885 小时前
搜索页面布局
前端·vue.js·node.js
Q_Q5110082857 小时前
python+uniapp基于微信小程序的旅游信息系统
spring boot·python·微信小程序·django·flask·uni-app·node.js
哆啦A梦15887 小时前
axios 的二次封装
前端·vue.js·node.js
Q_Q5110082857 小时前
python基于web的汽车班车车票管理系统/火车票预订系统/高铁预定系统 可在线选座
spring boot·python·django·flask·node.js·汽车·php
浪裡遊9 小时前
Nivo图表库全面指南:配置与用法详解
前端·javascript·react.js·node.js·php
weixin_4050233711 小时前
包资源管理器NPM 使用
前端·npm·node.js
Q_Q51100828517 小时前
python+django/flask婚纱摄影拍照管理系统
spring boot·python·django·flask·node.js·php
长空任鸟飞_阿康17 小时前
Node.js 核心模块详解:fs 模块原理与应用
前端·人工智能·ai·node.js
CS Beginner17 小时前
【node】运行windows7下的高版本node.js
node.js
水冗水孚20 小时前
fastify-sse-v2搭配EventSource实现SSE中的AI流式回复打字机效果&Fetch+ReadableStream+Chunked分块也可实现
node.js