Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Does vite provide a require.context-like API? #77

Closed
codebender828 opened this issue May 7, 2020 · 22 comments
Closed

Does vite provide a require.context-like API? #77

codebender828 opened this issue May 7, 2020 · 22 comments
Labels
enhancement New feature or request

Comments

@codebender828
Copy link

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.

@codebender828
Copy link
Author

codebender828 commented May 7, 2020

Perhaps an alternative would be to use fs.readdir?

@yyx990803 yyx990803 added the enhancement New feature or request label May 7, 2020
@lovetingyuan
Copy link

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

@Subwaytime
Copy link

Subwaytime commented Jun 5, 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?

@mesqueeb
Copy link

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!

@ariesjia
Copy link

ariesjia commented Jul 8, 2020

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

@luxueyan
Copy link

luxueyan commented Aug 4, 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, ... }
 */

@depsimon
Copy link

depsimon commented Nov 15, 2020

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

@anncwb
Copy link
Contributor

anncwb commented Jan 8, 2021

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

@yyx990803
Copy link
Member

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!)

@mesqueeb
Copy link

mesqueeb commented Jan 9, 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!!

@yyx990803
Copy link
Member

yyx990803 commented Jan 9, 2021

https://vitejs.dev/guide/features.html#glob-import

@buqiyuan
Copy link

@buqiyuan
Copy link

image

@yyx990803
Copy link
Member

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

@buqiyuan
Copy link

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

Oh, that's great! thanks

@richard1015
Copy link

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

牛🍺 !

@jinan5694
Copy link

/**
 * 路由自动注册
 * 遍历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

希望对大家能有帮助

@usu usu mentioned this issue Apr 16, 2021
3 tasks
@richard1015
Copy link

richard1015 commented Apr 21, 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 ...

@KarnaughK
Copy link

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;

@PeterAlfredLee
Copy link

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.

@LiuQixuan
Copy link

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)
  })
}

@github-actions
Copy link

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.

@github-actions github-actions bot locked and limited conversation to collaborators Jul 14, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests