My project uses a selection of .svg
files, chosen at random from a folder src/assets/svg
. The following code loads the filenames into an array so that individual images can be chosen later:
const svgImages = [''];
function setupLibrary() {
let modules;
if (process.env.NODE_ENV === 'development')
modules = import.meta.glob('/src/assets/svg/*.svg');
else
modules = import.meta.glob('/assets/*.svg');
for (const path in modules) {
svgImages.push(path);
}
}
This works fine in dev mode, but in production no files are found (modules
is empty). The build process adds all the .svg
files to the assets folder along with the .js
and .css
files.
I have also tried modules = import.meta.glob('/*.svg')
and simlar without success.
I have also looked at similar questions and answers, e.g. this one, this one and this one but without success. I have also read the vite docs but cannot find a solution.
vite.config.ts:
// Plugins
import vue from '@vitejs/plugin-vue'
import vuetify, { transformAssetUrls } from 'vite-plugin-vuetify'
// Utilities
import { defineConfig } from 'vite'
import { fileURLToPath, URL } from 'node:url'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue({
template: { transformAssetUrls }
}),
// https://github.com/vuetifyjs/vuetify-loader/tree/next/packages/vite-plugin
vuetify({
autoImport: true,
}),
],
define: { 'process.env': {} },
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
},
extensions: [
'.js',
'.json',
'.jsx',
'.mjs',
'.ts',
'.tsx',
'.vue'
],
},
server: {
port: 5173,
},
})
2
Answers
I have changed my approach and solved it as below. It has required renaming all (44)
.svg
files assvg1.svg
,svg2.svg
etc, which is tedious (but took me only 10 minutes, not 10 hours I tried with other methods!)This works both from the local
dist
folder (usingnpm run build
thennpm run preview
), and also on the production server.If there was an easy way of finding the number of files in that folder, or better still to get an array listing their names, the method would be much improved.
Did you try with
{ eager: true }
like this