You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel/Vue/Vite中import.meta.glob导入的图片构建后存在却无法显示

问题分析

在Laravel + Vite环境中,import.meta.glob导入资源的路径处理逻辑和纯Vite不同,核心问题在于:

  • 手动设置的publicPath: ''破坏了Laravel Vite插件默认的资源路径映射规则
  • 导入时使用绝对路径/resources/images/...,导致Laravel Vite无法正确解析为构建后的发布路径

解决步骤

1. 修正vite.config.js配置

移除publicPath: ''配置项,Laravel Vite插件会自动处理资源的公共路径,确保构建后的资源指向/build/assets/:

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue'
import eslintPlugin from 'vite-plugin-eslint'
import { NodeGlobalsPolyfillPlugin } from '@esbuild-plugins/node-globals-polyfill'

export default defineConfig({
    server: {
        hmr: {
            host: 'localhost',
        },
        watch: {
            usePolling: true,
        }
    },
    plugins: [
        laravel({
            input: [
                'resources/js/main.js',
                'resources/scss/main.scss'
            ],
            refresh: true,
        }),
        vue({
            template: {
                transformAssetUrls: {
                    base: null,
                    includeAbsolute: false,
                },
            },
        }),
        eslintPlugin(),
    ],
    optimizeDeps: {
        esbuildOptions: {
            define: {
                global: 'globalThis'
            },
            plugins: [
                NodeGlobalsPolyfillPlugin({
                    buffer: true
                })
            ],
        }
    },
    build: {
        assetsInlineLimit: 0
    }
});

2. 调整import.meta.glob的导入逻辑

使用相对路径导入资源,并正确解析Vite返回的资源URL:

<script setup>
// 根据组件所在位置调整相对路径,示例假设组件在resources/js/components下
const imageModules = import.meta.glob('../../images/drivers/2023/*', { eager: true });

// 转换为{ 文件名: 最终资源URL }的格式
const driverImages = Object.fromEntries(
  Object.entries(imageModules).map(([path, module]) => {
    const fileName = path.split('/').pop();
    return [fileName, module.default];
  })
);
</script>

<template>
  <div v-for="(url, name) in driverImages" :key="name">
    <img :src="url" :alt="name">
  </div>
</template>

3. 验证构建结果

执行npm run build后,检查public/build/assets目录下是否存在目标图片,再打开浏览器查看图片的src属性,确认路径为/build/assets/[hash]-[filename]格式的正确路径。

补充说明

  • 如果组件位置不同,需要调整相对路径的层级,确保准确指向resources/images/drivers/2023/目录
  • 若需按需加载资源,可移除{ eager: true }选项,改用异步函数调用模块加载

内容的提问来源于stack exchange,提问作者Slasher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 01:45:24