
当 HTML 文件与编译后的 JavaScript 文件位于不同目录时,浏览器 404 报错通常源于服务器根目录与资源相对路径不匹配;关键在于确保所有 引用的文件均位于 HTTP 服务器实际暴露的公共可访问路径下。
当 html 文件与编译后的 javascript 文件位于不同目录时,浏览器 404 报错通常源于服务器根目录与资源相对路径不匹配;关键在于确保所有 `<script>` 引用的文件均位于 http 服务器实际暴露的公共可访问路径下。</script>
在你当前的项目结构中:
dairyproducts.github.io/ ├── package.json ├── public/ ← 实际 Web 服务器的「内容根目录」(即 http-server 默认服务的起点) │ ├── index.html ← 浏览器通过 http://localhost:8080/index.html 访问此文件 ├── dist/ │ └── index.js ← 此路径未被服务器直接公开,/dist/ 不在 public/ 下 → 404!
虽然 <script src="../dist/index.js"></script> 在文件系统层面看似合理(public/index.html 的上一级是项目根,再进 dist/),但 HTTP 服务器(如 http-server)并不按磁盘路径解析 ..,而是严格以启动时指定的「服务根目录」为基准处理所有请求。
你执行的是 http-server ./ -p 8080,这意味着服务器根目录是项目根(dairyproducts.github.io/),此时:
-
/index.html→ 404(因为index.html实际在public/下) -
/public/index.html→ ✅ 可访问 -
/dist/index.js→ ✅ 可访问(若dist/在根目录下) - 但
public/index.html中的<script src="../dist/index.js"></script>会被浏览器解析为:从当前 URL 路径向上跳一级后拼接dist/index.js。
假设你访问的是http://localhost:8080/public/index.html,那么../dist/index.js→http://localhost:8080/dist/index.js—— 这个路径确实存在(因dist/在根下),理论上应成功。但你的测试显示失败,说明实际访问入口并非/public/index.html。
⚠️ 关键矛盾点:你提到 “http-server ./ -p 8080 --cors serves a file directory of the root folder, and when the public folder is navigated to the HTML file loads the index.js as expected” —— 这表明你是通过浏览器手动点击 public/ 文件夹进入 index.html 的,此时浏览器地址栏显示的是类似 http://localhost:8080/public/,而 index.html 是自动加载的(服务器默认返回 index.html)。此时页面内 <script src="../dist/index.js"></script> 解析为 http://localhost:8080/dist/index.js,✅ 成功。
但如果你直接访问 http://localhost:8080/public/index.html(显式路径),同样应成功。若仍 404,请检查浏览器开发者工具(F12)→ Network 标签页,确认请求的 JS 路径是否确实是 /dist/index.js,以及响应状态码和服务器返回的实际目录结构。
✅ 推荐生产就绪方案(最佳实践):
-
统一静态资源出口:将
dist/内容复制到public/下(使用构建脚本):// package.json "scripts": { "build": "tsc && cp -r dist/* public/", "dev": "concurrently \"tsc -w\" \"http-server public/ -p 8080\"" }然后在
public/index.html中使用:<script src="index.js"></script><!-- 同目录,最简健壮 -->
-
或启动服务器时直接指定
public/为根目录:http-server public/ -p 8080 --cors
此时:
- 访问
http://localhost:8080/→ 自动加载public/index.html - 所有资源路径需相对于
public/:
✅<script src="index.js"></script>(若index.js在public/下)
✅<script src="js/index.js"></script>(若public/js/index.js)
❌<script src="../dist/index.js"></script>(..会跳出public/,服务器拒绝访问)
- 访问
(进阶)使用
--proxy或重写规则(如配合serve或vite)实现 SPA 路由兼容,但对静态 JS 加载非必需。
? 总结:Web 资源路径解析 = 浏览器当前 URL 路径 + HTML 中 src 的相对路径,与磁盘结构无关;http-server 的 -p 参数只指定端口,./ 才决定服务根。永远确保 <script></script> 的最终解析 URL 对应服务器实际可返回的文件路径。调试时务必打开 DevTools → Network,看真实请求地址与响应,而非仅依赖文件树想象。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











