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

基于Vite构建多共享源码应用时Href路径异常排查

Vite多应用构建资源路径错误解决

问题现象

作为Vite新手,我需要构建多个共享组件的应用,项目结构为src目录下包含modules子目录,每个子目录对应一个独立应用并包含HTML入口文件。此前开发运行正常,但构建后生成的HTML文件中资源路径出现混合分隔符的错误,示例如下:

<script type="module" crossorigin src="/assets/modules/modules\VPlayerList\index-74e8dd8e.js"></script>

路径中同时出现正斜杠/和反斜杠\,导致资源无法正确加载。

当前Vite配置

import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import path, { resolve } from 'path'
import glob from 'glob';

export default defineConfig({
  plugins: [vue(), vueJsx()],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  build: {
    rollupOptions: {
      input: Object.fromEntries(
        glob.sync("src/modules/**/*.html").map((file:string) => [
          path.relative(
            "src",
            file.slice(0, file.length - path.extname(file).length)
          ),
          fileURLToPath(new URL(file, import.meta.url)),
        ])
      ),
      output: {
        chunkFileNames: 'assets/js/[name]-[hash].js',
        entryFileNames: 'assets/modules/[name]-[hash].js',
        dir: "dist"
      }
    },
  },
})

问题原因

路径错误源于系统分隔符不统一:

  • glob.sync在Windows环境下返回的路径会使用反斜杠\
  • path.relative生成的路径也会采用系统默认分隔符(Windows为\)
  • 但Vite/Rollup要求URL路径必须使用正斜杠/,最终导致两种分隔符混合出现,形成错误路径格式。

解决方案

1. 统一路径分隔符

修改rollupOptions.input部分,将生成的入口名称中的反斜杠替换为正斜杠:

input: Object.fromEntries(
  glob.sync("src/modules/**/*.html").map((file:string) => [
    // 替换所有反斜杠为正斜杠
    path.relative(
      "src",
      file.slice(0, file.length - path.extname(file).length)
    ).replace(/\\/g, '/'),
    fileURLToPath(new URL(file, import.meta.url)),
  ])
),

2. 优化模块路径结构(可选)

在output配置中添加preserveModulesRoot,明确模块根目录,避免路径中重复出现modules前缀:

output: {
  chunkFileNames: 'assets/js/[name]-[hash].js',
  entryFileNames: 'assets/modules/[name]-[hash].js',
  dir: "dist",
  // 指定模块根目录,精简输出路径
  preserveModulesRoot: 'src/modules'
}

修改完成后重新构建,HTML中的资源路径会统一为正斜杠格式,示例如下:

<script type="module" crossorigin src="/assets/modules/VPlayerList/index-74e8dd8e.js"></script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 22:50:40