| 119 | // ==================== HTML 复制并替换引用 ==================== |
| 120 | |
| 121 | function copyHTML(jsHash, cssHash) { |
| 122 | const html = fs.readFileSync(HTML_SRC, 'utf-8'); |
| 123 | |
| 124 | // 构建输出文件名 |
| 125 | // 有 hash 时:main.ABC123.css;无 hash(dev)时:main.css |
| 126 | const cssName = cssHash ? `main.${cssHash}.css` : 'main.css'; |
| 127 | const jsName = jsHash ? `main.${jsHash}.js` : 'main.js'; |
| 128 | |
| 129 | // 将 <link> 和 <script> 的 href/src 替换为构建产物文件名 |
| 130 | // 匹配源文件中的 styles/main.css 和 js/main.ts |
| 131 | const updated = html |
| 132 | .replace( |
| 133 | /<link\s+[^>]*href="[^"]*\.css"/, |
| 134 | `<link rel="stylesheet" href="${cssName}"` |
| 135 | ) |
| 136 | .replace( |
| 137 | /<script\s+[^>]*\btype="module"[^>]*\bsrc="[^"]*\.[jt]s"[^>]*>|<script\s+[^>]*\bsrc="[^"]*\.[jt]s"[^>]*\btype="module"[^>]*>/, |
| 138 | `<script src="${jsName}" type="module">` |
| 139 | ); |
| 140 | |
| 141 | fs.writeFileSync(path.join(OUT_DIR, 'index.html'), updated); |
| 142 | console.log(` 📄 HTML → index.html`); |
| 143 | } |
| 144 | |
| 145 | // ==================== 开发服务器 ==================== |
| 146 | |