Subscribe on changes!

Does vite provide a require.context-like API?

avatar
May 7th 2020

Is your feature request related to a problem? Please describe. I would like to be able to dynamically read the file objects inside specific directory. Webpack provides API like require.context in order to achieve this.

Describe the solution you'd like Is there any way within vite that one can perform something similar to require.context to read and parse file objects

Additional context This would be useful to create dynamic route building with Vue router by reading the contents of the directory.

avatar
May 7th 2020

Perhaps an alternative would be to use fs.readdir?

avatar
May 20th 2020

like parcel: import imgmap from "./path/*.png"

avatar
Jun 5th 2020

Any update on this Feature? I am currently trying to figure out a way to autoload Vuex Modules and Vue Components.

Only good Solution that i found by now is to generate a JSON File (on build) with fs and globby and then register the Modules and Components in Runtime. For HMR a Custom Vite Server Plugin would be needed i assume..

Is there any other possible Idea for this?

avatar
Jun 24th 2020

I am also looking for a substitute for require.context to be able to migrate to Vite. I tried this rollup plugin: https://github.com/elcarim5efil/rollup-plugin-require-context But it doesn't seem to work out of the box.

Any advise is much appreciated!

avatar
Jul 8th 2020

rollup plugin can be used in build mode, but in dev mode no rollup, how to support this feature?

avatar
Aug 4th 2020

I haven't thought of nice resolutions for this. But I have written a transform for this。https://github.com/luxueyan/vite-transform-globby-import. It support both dev and build mode. It only replaces 'globby import' simplely. Example:

import routes from '../pages/**/route.ts'
import imgs from '/@/assets/image/**/*.@(jpg|png)'
// These will be replaced to:
/* 
 * import * as routes0 from '/@/pages/route.ts'
 * import * as routes1 from '/@/pages/demo/route.ts'
 * ...
 * const routes = { routes0, routes1, ... }
 * import * as imgs0 from '/@/assets/image/demo.jpg'
 * import * as imgs1 from '/@/assets/image/demo/demo.png'
 * ...
 * const imgs = { imgs0, imgs1, ... }
 */
avatar
Nov 15th 2020

Also interested. Would be useful for autoloading Vuex modules for instance.

avatar
Jan 8th 2021

I wrote one that can support dynamic import and other functions https://github.com/vbenjs/vite-plugin-import-context. Welcome to try

avatar
Jan 9th 2021

Renamed to glob import in 8d8e2cc (I realize the syntax and transform is very similar to @luxueyan 's plugin only after I have implemented it!)

avatar
Jan 9th 2021

Can anyone give an example of how to use the newly implemented glob import? I'd like to import all .svg files in a folder in my project. Thanks!!

avatar
Jan 20th 2021

image

avatar
Jan 20th 2021
avatar
Jan 20th 2021

The syntax has been updated https://vitejs.dev/guide/features.html#glob-import

Oh, that's great! thanks

avatar
Feb 23rd 2021

The syntax has been updated https://vitejs.dev/guide/features.html#glob-import

牛🍺 !

avatar
Apr 8th 2021
/**
 * 路由自动注册
 * 遍历views目录下所有 *.route.ts 文件,内部为路由信息
 * https://cn.vitejs.dev/guide/features.html#glob-import
 */
import { RouteRecordRaw } from "vue-router"

const modules = import.meta.globEager('/src/views/**/*.route.ts')
const autoRegisteredRoutes: RouteRecordRaw[] = []
for (const path in modules) {
  autoRegisteredRoutes.push(modules[path].default)
}

export { autoRegisteredRoutes }

import.meta.globEager 这个方法是同步的,等同于require.context

希望对大家能有帮助

avatar
Apr 21st 2021

webpack vs vite glob

/** webpack */
// const files = require.context('@/packages', true, /demo\.vue$/);
// files.keys().forEach(component => {
//   const componentEntity = files(component).default;
//   routes.push({
//     path: `/${componentEntity.baseName}`,
//     name: componentEntity.baseName,
//     component: componentEntity
//   });
// });

/** vite */
const modulesPage = import.meta.glob('/src/packages/**/demo.vue');
for (const path in modulesPage) {
  let name = (/packages\/(.*)\/demo.vue/.exec(path) as any[])[1];
  routes.push({
    path: '/' + name,
    component: modulesPage[path],
    name
  });
}

source code ...

avatar
May 7th 2021

vuex: webpack vs vite glob

/** webpack */
const files = require.context(".", false, /\.js$/);
const modules = {};

files.keys().forEach(key => {
    if (key === "./index.js") return;
    modules[key.replace(/(\.\/|\.js)/g, "")] = files(key).default;
});

export default modules;
/** vite */
const files = import.meta.globEager("./*.js");

const modules = {};
for (const key in files) {
    // if (key === "./index.js") continue;
    modules[key.replace(/(\.\/|\.js)/g, "")] = files[key].default;
}
console.log(files, modules);

export default modules;
avatar
Jun 10th 2021

Hi folks. Recently I implemented a vite plugin that can handle the require.context here. It's implemented by regexp search. Hope this can help a little bit.

BTW : contributions are welcome.

avatar
Jun 20th 2021

vite 2.0 docs Glob import

Vite supports importing multiple modules from the file system via the special import.meta.glob function:

const modules = import.meta.glob('./dir/*.js') The above will be transformed into the following:

// code produced by vite
const modules = {
  './dir/foo.js': () => import('./dir/foo.js'),
  './dir/bar.js': () => import('./dir/bar.js')
}

You can then iterate over the keys of the modules object to access the corresponding modules:

for (const path in modules) {
  modules[path]().then((mod) => {
    console.log(path, mod)
  })
}
avatar
Jul 14th 2021

This issue has been locked since it has been closed for more than 14 days.

If you have found a concrete bug or regression related to it, please open a new bug report with a reproduction against the latest Vite version. If you have any other comments you should join the chat at Vite Land or create a new discussion.