3

I'm looking for way to make the same logic of require.context of webpack in vitejs, I've found this plugin named vite-plugin-import-context, I tried it out but there's something that I didn't understand which is import dynamicImport from '../src/index' in the basic usage :

import { UserConfigExport } from 'vite';
import vue from '@vitejs/plugin-vue';

import dynamicImport from '../src/index';// <-- this is not described

export default (): UserConfigExport => {
  return {
    plugins: [vue(), dynamicImport(/*options*/)],
  };
};

5 Answers 5

8

require should never be used in source code when using Vite. It's ESM only. For Vite v2, import.meta.globEager can be used. For Vite >v2, import.meta.globEager is deprecated. Use import.meta.glob('*', { eager: true }) instead.

Sign up to request clarification or add additional context in comments.

Comments

3

import.meta.glob() is webpack alternative of require.context() . It has been added in vite since v2.3.4 .

Here is a link to the doc https://vitejs.dev/guide/features.html#glob-import

Comments

3

Here is how I import all the plugins/modules:

main.ts

import { createApp } from 'vue';
import App from './App.vue';

const app = createApp(App);

// styles here
import '@/assets/styles/tailwind.css';
import '@/assets/styles/main.scss';

// install all modules under `modules/`
Object.values(
  import.meta.glob<{ install: (ctx: any) => void }>('/src/modules/*.ts', { eager: true })
).forEach((module) => module.install?.(app));

app.mount('#app');

and here is how I keep things ready in my modules folder to export:

modules/pinia.ts

import { createPinia } from 'pinia';

export const install = (app: any) => {
  app.use(createPinia());
};

modules/router.ts

import type { RouteRecordRaw } from 'vue-router';
import { createRouter, createWebHashHistory } from 'vue-router';

import generatedRoutes from '~pages';
import { setupLayouts } from 'virtual:generated-layouts';

const routes: RouteRecordRaw[] = setupLayouts(generatedRoutes);

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

export const install = (app: any) => {
  app.use(router);
};

Comments

1

Yep, that example is directly taken from examples folder in the repo so it works only in that repo.

If you install the plugin via npm or yarn, the line should look like import dynamicImport from 'vite-plugin-import-context'

Comments

0

just use:

const iconsModule = import.meta.glob('@/path/*.svg');

then you can iterate through paths and get the file name with or without format name

for (const path in iconsModule) {
            const icon = path.split('/').slice(-1)[0];
            this.icons.push(icon);
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.