2
0
Просмотр исходного кода

✨ feat(server): 实现生产环境模板资源自动注入

- 读取 Vite manifest.json 获取构建产物信息
- 自动生成并注入 CSS 链接到 HTML 模板
- 自动替换入口脚本为构建后的产物路径
- 添加基础路径处理支持,确保资源 URL 正确性
- 增加错误捕获与处理机制,提升生产环境稳定性
yourname 7 месяцев назад
Родитель
Сommit
c6a9741aad
1 измененных файлов с 41 добавлено и 3 удалено
  1. 41 3
      server.js

+ 41 - 3
server.js

@@ -248,9 +248,47 @@ app.use(async (c) => {
       render = module.render;
     } else {
       // 生产环境:使用缓存的模板
-      // const module = (await import('./dist/server/index.js'))
-      const module = (await import('/src/server/index.tsx'))
-      template = module.template;
+      // const module = (await import('/src/server/index.tsx'))
+      // template = module.template;
+
+       // 读取 manifest.json 并处理模板
+      try {
+        // 读取 manifest
+        const manifestPath = new URL('./dist/client/.vite/manifest.json', import.meta.url);
+        const manifestContent = await fs.readFile(manifestPath, 'utf-8');
+        const manifest = JSON.parse(manifestContent);
+
+        // 获取 index.html 对应的资源信息
+        const indexManifest = manifest['index.html'];
+        if (!indexManifest) {
+          throw new Error('manifest 中未找到 index.html 入口配置');
+        }
+
+        // 读取原始模板
+        const module = await import('./dist/server/index.js');
+        let template = module.template;
+
+        // 替换 CSS 链接
+        const cssLinks = indexManifest.css?.map(cssFile => {
+          // 结合基础路径生成完整 URL(处理 base 前缀)
+          const cssUrl = new URL(cssFile, baseUrl).pathname;
+          return `<link href="${cssUrl}" rel="stylesheet" />`;
+        }).join('\n') || ''; // 无 CSS 则清空
+
+        // 替换入口脚本
+        const jsEntryPath = new URL(indexManifest.file, baseUrl).pathname;
+        const entryScript = `<script type="module" src="${jsEntryPath}"></script>`;
+
+        // 执行替换
+        template = template
+          .replace(/<link href='\/src\/style.css' rel="stylesheet" \/>/, cssLinks)
+          .replace(/<script type="module" src="\/src\/client\/index.tsx"><\/script>/, entryScript);
+
+      } catch (err) {
+        console.error('生产环境模板处理失败:', err);
+        throw err; // 终止启动,避免使用错误模板
+      }
+
       render = module.render;
     }