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

如何使用Vite将JS Chunks注入<body>标签而非<head>标签

解决Vite构建React应用时JS Chunks注入而非的问题

首先明确:你之前配置的optimizeDeps.inject仅作用于开发阶段的预构建依赖注入位置,对npm run build生成的生产环境代码完全无效,所以这个配置无法解决你的问题。

下面是针对生产构建的有效解决方案:

1. 检查并修正HTML模板的入口脚本位置

确保你的index.html中,入口脚本是放在<body>标签内部(建议在</body>之前),而不是<head>里。正确的模板结构示例:

<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
    <!-- 入口脚本必须放在body内 -->
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>

2. 使用Vite的transformIndexHtml钩子统一调整脚本位置

如果动态导入的chunk仍被注入到<head>,可以通过Vite的transformIndexHtml钩子,将所有脚本标签移动到<body>末尾。修改vite.config.js如下:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  // 重写HTML,将所有脚本标签移到body末尾
  transformIndexHtml: (html) => {
    // 提取页面中所有script标签
    const scriptTags = html.match(/<script[^>]*>.*?<\/script>/g) || [];
    // 移除原HTML中的所有script标签
    const htmlWithoutScripts = html.replace(/<script[^>]*>.*?<\/script>/g, '');
    // 将所有script标签追加到body结束标签前
    return htmlWithoutScripts.replace('</body>', `${scriptTags.join('')}</body>`);
  },
});

3. 可选:配置Rollup输出规则(针对动态chunk)

如果是动态导入的chunk路径或命名导致的注入异常,可以在Rollup配置中规范输出路径,辅助Vite正确注入脚本:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  build: {
    rollupOptions: {
      output: {
        // 统一chunk和入口脚本的输出路径
        chunkFileNames: 'assets/js/[name]-[hash].js',
        entryFileNames: 'assets/js/[name]-[hash].js',
      },
    },
  },
});

执行npm run build重新构建后,所有JS Chunks应该会被正确注入到<body>标签内。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 03:31:12