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

如何在静态多页站点中自动引用Vite构建输出的资源文件

解决方案

方法一:配置Vite多页面入口(推荐)

这是Vite官方支持的多页站点处理方式,能让Vite自动为所有指定的HTML页面注入构建后的JS/CSS引用,无需额外脚本。

  1. 修改vite.config.js,通过build.rollupOptions.input定义所有HTML入口:
import { defineConfig } from 'vite';
import path from 'path';

export default defineConfig({
  build: {
    rollupOptions: {
      input: {
        index: path.resolve(__dirname, 'index.html'),
        about: path.resolve(__dirname, 'about.html'),
        contact: path.resolve(__dirname, 'contact.html')
        // 根目录下其他HTML页面依次添加
      }
    }
  }
});
  1. 若页面数量较多,可自动扫描根目录下的HTML文件,避免手动维护入口列表:
import { defineConfig } from 'vite';
import fs from 'fs';
import path from 'path';

function getHtmlEntries() {
  const entries = {};
  // 扫描根目录所有文件
  const rootFiles = fs.readdirSync(__dirname);
  
  rootFiles.forEach(file => {
    if (file.endsWith('.html')) {
      const entryName = file.replace('.html', '');
      entries[entryName] = path.resolve(__dirname, file);
    }
  });
  return entries;
}

export default defineConfig({
  build: {
    rollupOptions: {
      input: getHtmlEntries()
    }
  }
});

配置完成后,执行npm run build,Vite会自动为每个HTML页面注入对应的带hash的资源引用。

方法二:Postbuild脚本替换(备用方案)

如果因特殊场景无法使用多页面入口配置,可通过构建后脚本批量替换HTML中的令牌来注入资源。

  1. 开启Vite的manifest生成功能,修改vite.config.js:
import { defineConfig } from 'vite';

export default defineConfig({
  build: {
    manifest: true // 构建后在dist目录生成manifest.json,记录资源映射关系
  }
});
  1. 编写Node脚本postbuild.js,读取manifest并批量更新HTML文件:
const fs = require('fs');
const path = require('path');

// 读取dist目录下的manifest文件
const manifestPath = path.resolve(__dirname, 'dist/manifest.json');
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));

// 获取需要注入的资源路径(以src/main.js为例,根据你的实际入口文件调整)
const mainJs = manifest['src/main.js']?.file;
const mainCss = manifest['src/main.js']?.css?.[0];

// 遍历dist目录下所有HTML文件,替换预定义令牌
function updateHtmlFiles(dir) {
  const files = fs.readdirSync(dir);
  files.forEach(file => {
    const fullPath = path.join(dir, file);
    const stats = fs.statSync(fullPath);
    
    if (stats.isDirectory()) {
      updateHtmlFiles(fullPath);
    } else if (file.endsWith('.html')) {
      let htmlContent = fs.readFileSync(fullPath, 'utf8');
      
      // 替换HTML中的<!-- VITE_JS -->和<!-- VITE_CSS -->令牌
      if (mainJs) {
        htmlContent = htmlContent.replace('<!-- VITE_JS -->', `<script type="module" src="/${mainJs}"></script>`);
      }
      if (mainCss) {
        htmlContent = htmlContent.replace('<!-- VITE_CSS -->', `<link rel="stylesheet" href="/${mainCss}">`);
      }
      
      fs.writeFileSync(fullPath, htmlContent, 'utf8');
      console.log(`已更新资源引用:${fullPath}`);
    }
  });
}

updateHtmlFiles(path.resolve(__dirname, 'dist'));
  1. 在package.json中添加构建后执行脚本的命令:
{
  "scripts": {
    "build": "vite build && node postbuild.js"
  }
}

之后在所有需要注入资源的HTML页面中,添加对应的令牌即可,比如在<head>中加入<!-- VITE_CSS -->,在<body>末尾加入<!-- VITE_JS -->。

方案对比

  • 方法一:官方原生支持,无需额外维护脚本,资源注入逻辑由Vite统一处理,稳定性最高,优先推荐。
  • 方法二:适合特殊场景(如HTML页面不在根目录、需自定义注入逻辑等),但需要维护令牌和脚本,灵活性更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 10:51:27