Vite中使用glob导入组件后为什么路径报错?

诸葛英洁 阅读 68

大家好,我在用Vite+React项目里用glob导入组件时遇到了问题。按照网上的方法写了这样的代码:


import { glob } from 'glob';
const components = glob.sync('./components/*.jsx').map(path => 
  require(path).default
);

但启动时提示Cannot find module 'D:/project/components/Button.jsx',明明文件路径是对的。试过把路径改成绝对路径、加./都不行,换成Webpack应该没问题吧?是不是Vite处理glob导入需要额外配置?

我来解答 赞 10 收藏
二维码
手机扫码查看
2 条解答
西门建英
这个问题很常见,核心原因是你把 Webpack 的写法搬到 Vite 里了。

根本问题有两个:

1. Vite 是基于 ESM 的,不支持 require() 语法
2. glob.sync 返回的只是字符串路径,Vite 没办法在构建时做静态分析,所以找不到模块

Vite 有自己的 glob 导入方式,用 import.meta.glob 就行:

// 改成 Vite 的写法
const modules = import.meta.glob('./components/*.jsx', { eager: true });

const components = Object.entries(modules).map(([path, mod]) => ({
path,
component: mod.default
}));


如果不需要立即加载(懒加载):

const modules = import.meta.glob('./components/*.jsx');

// 使用时才加载
const loadComponent = async (path) => {
const mod = await modules[path]();
return mod.default;
};


关键点就是 { eager: true } 这个选项。加上它会同步加载所有匹配的模块,返回的就是实际的组件;不加的话返回的是一个函数,调用时才加载。

不用换 Webpack,Vite 自带这个功能就是干这个用的。
点赞
2026-03-19 10:14
建杰酱~
你遇到的问题是因为 Vite 对文件路径的处理机制和 Webpack 不一样。Vite 本身并不支持直接使用 Node.js 的 glob 模块来动态导入文件,它需要在构建时就能静态分析出模块的依赖关系,而 glob.sync 这种方式是运行时的操作,Vite 无法解析。

试试这个方法:用 Vite 提供的 import.meta.glob 来替代 glob。这是 Vite 内置的功能,专门用来处理这种场景。代码可以改成这样:


const modules = import.meta.glob('./components/*.jsx');

const components = Object.keys(modules).map(async (path) => {
const module = await modules[path]();
return module.default;
});


这里的关键点是 import.meta.glob 会返回一个对象,键是匹配到的文件路径,值是一个返回 Promise 的函数,调用后可以加载对应的模块。

另外需要注意的是,import.meta.glob 默认是懒加载的,所以需要用 await 来获取模块内容。如果你希望在构建时就把所有模块打包进来,可以在 import.meta.glob 的第二个参数传入 { eager: true },像这样:


const modules = import.meta.glob('./components/*.jsx', { eager: true });

const components = Object.keys(modules).map((path) => {
return modules[path].default;
});


这样做的话,modules 的值会直接是导入的模块对象,而不是一个函数。

总结一下,Vite 和 Webpack 的工作方式不同,不能直接用 Node.js 的 glob,换成 import.meta.glob 就能解决问题了。这其实是 Vite 的一个特性,虽然刚开始可能有点不习惯,但用熟了会觉得挺方便的。
点赞 5
2026-02-14 10:05