jpkleemans / vite-svg-loader

Vite plugin to load SVG files as Vue components
MIT License
555 stars 59 forks source link

import.meta.globEager not working #52

Closed lisonge closed 1 year ago

lisonge commented 2 years ago
// vite.config.ts
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import svgLoader from 'vite-svg-loader';
import legacy from '@vitejs/plugin-legacy';
import hmrFollow from 'vite-plugin-hmr-follow';
import path from 'path';
export default defineConfig({
  plugins: [
    vue(),
    svgLoader(),
    legacy({
      targets: ['defaults', 'not IE 11'],
    }),
    hmrFollow(),
  ],
  server: {
    host: '127.0.0.1',
    port: 8001,
  },
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
    },
  },
  build: {
    sourcemap: false,
  },
});

// --------------------------------------
// any_file.ts

const modules = import.meta.globEager('@/assets/svg/*.svg', { as: 'url' });
  for (const path in modules) {
    const mod = modules[path];
    console.log(path, mod);
    // got <string>, <object>, instead of <string>, <string>
  }
lisonge commented 2 years ago

how to make import.meta.globEager work with vite-svg-loader ?

jpkleemans commented 2 years ago

import.meta.globEager should work just fine with vite-svg-loader. Can you reproduce the problem in a CodeSandbox?

lisonge commented 2 years ago

@jpkleemans

codesandbox not working with import.meta.globEager

https://codesandbox.io/s/funny-bartik-w5ywxn?file=/src/main.ts:44-65

image

reproduce source code https://github.com/lisonge/svg-loader-test.git

lisonge commented 2 years ago

i expect import.meta.globEager('@/assets/svg/*.svg', { as: 'url' }) is Record<string, string>, but i got Record<string, Module>

lisonge commented 2 years ago

https://github.com/lisonge/svg-loader-test.git

pnpm i
pnpm run serve

will got

image

lisonge commented 2 years ago

online demo -> https://stackblitz.com/edit/vitejs-vite-m8rdbw?file=src%2Fmain.ts,vite.config.ts,index.html&terminal=dev

image

jpkleemans commented 2 years ago

Thanks for your reply and demo. I see now indeed that loading as url doesn't work. I'll have to dig in to the Import Reflection syntax of import.meta.globEager to see how to make it work. If you'd like to help by opening a PR, that is of course also very welcome!

lisonge commented 2 years ago

@jpkleemans

https://github.com/vitejs/vite/blob/v2.9.13/packages/vite/src/node/importGlob.ts#L52

vite@^2 not api to get query for import.meta.globEager

vite@^3 is work with https://github.com/vitejs/vite/blob/v3.0.0-beta.4/docs/guide/features.md#custom-queries

abigmiu commented 1 year ago

vite3 以上是 import.meta.glob('source', { eager: true })。 用 ts 的时候会提示 globEage 已经废弃了