import.meta.glob匹配所有tsx文件或者jsx文件
时间: 2023-11-10 12:55:41 浏览: 89
vite vue3 import.meta.glob动态路由
使用import.meta.glob可以匹配所有.tsx或.jsx文件。在Vite项目中,可以使用以下代码来实现这个功能:
```tsx
import { import.meta } from 'vite'
import loadable from '@loadable/component'
const modules = import.meta.glob('./src/**/*.@(tsx|jsx)')
function loadModules(): Promise<any>[] {
const promises: Promise<any>[] = []
for (const path in modules) {
promises.push(modules[path())
}
return promises
}
async function loadComponents(): Promise<JSX.Element[]> {
const components: JSX.Element[] = []
try {
const modules = await Promise.all(loadModules())
modules.forEach(module => {
const Component = loadable(() => module)
components.push(<Component />)
})
} catch (error) {
console.error('Error loading components:', error)
}
return components
}
export default loadComponents
```
这段代码会使用import.meta.glob来匹配所有以.tsx或.jsx为后缀的文件,然后通过循环加载这些模块,并使用loadable库来实现路由动态导入。最后,将加载的组件渲染到页面上。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [替代 webpack?带你了解 snowpack 原理,你还学得动么](https://blog.csdn.net/liuyan19891230/article/details/107527268)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"]
- *2* [vite+@loadable/component配置路由动态导入](https://blog.csdn.net/fighting_sunnyGirl/article/details/119727156)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文