vue使用import.meta.glob动态导入多个模块方式
作者:吃代码长大的前端
文章介绍了Vite提供的`import.meta.glob`功能,用于动态导入多个模块,它通过glob模式匹配文件,返回一个对象,键为文件路径,值为返回Promise的动态导入函数,支持eager模式直接导入和as选项指定导入方式,如原始字符串或文件URL,适用于Vite或Rollup项目
import.meta.glob 是 Vite 提供的一个功能,用于在构建时动态导入多个模块。
它通过 glob 模式匹配文件,返回一个对象,键为文件路径,值为返回 Promise 的动态导入函数。
语法与参数
const modules = import.meta.glob(globPattern, options);
- globPattern:
字符串或字符串数组,支持 glob 模式(如 './modules/*.js')。
options(可选):
eager:若为true,直接导入模块而非返回 Promise(默认false)。as:指定导入方式,如'raw'(原始字符串)或'url'(文件 URL)。
使用示例
动态导入文件
匹配 src/features 下所有 .js 文件,按需加载:
const features = import.meta.glob('./src/features/*.js');
for (const path in features) {
features[path]().then((module) => {
console.log(module.default);
});
}
直接导入(eager 模式)
静态加载所有匹配模块:
const modules = import.meta.glob('./lib/*.js', { eager: true });
console.log(modules['./lib/utils.js'].default);
导入为原始内容
获取文件原始字符串或 URL:
const rawFiles = import.meta.glob('./assets/*.txt', { as: 'raw' });
const fileUrls = import.meta.glob('./images/*.png', { as: 'url' });
注意事项
- 仅适用于 Vite 或 Rollup 项目,需在构建时确定模块路径。
- 动态导入的模块会代码分割,生成独立 chunk。
- 路径需相对于当前文件,且需包含扩展名(如
.js)。
与import.meta.globEager的区别
Vite 4 已弃用 globEager,推荐使用 { eager: true } 选项替代。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
