Bun生成CSS分块文件路径错误,前后端分目录时如何修复?
Bun全栈服务器CSS分块路径错误的正规解决方案
问题现象
按照Bun官方教程部署全栈开发服务器时,页面无样式,CSS和JS分块文件返回404。Bun自动生成的HTML中资源路径不符合预期:
- 期望路径:
<link rel="stylesheet" crossorigin href="/chunk-4hkzj3px.css"> - 实际生成路径:
<link rel="stylesheet" crossorigin href="/../backend/chunk-4hkzj3px.css">
原因分析
Bun处理HTML导入时,会自动将原HTML中的样式表、脚本引用替换为分块后的chunk*.css/chunk*.js文件。路径错误的核心原因是服务器从backend目录启动,Bun基于当前工作目录计算资源输出路径,导致生成了包含../backend的错误路径。
文件结构
repo ├── backend │ └── index.ts ├── frontend │ ├── index.html │ ├── scriptOfIdx.js │ └── styleOfIdx.css
启动方式
在repo/backend/目录下执行:
npx bun index.ts
核心服务代码
// MY TYPESCRIPT CODE import homepage from "../frontend/index.html"; const port = 3000; const server = Bun.serve({ port: port, // Add HTML imports to `static` static: { // Bundle & route index.html to "/" "/": homepage, }, development: true, // Handle API requests async fetch(req) { console.log(req.url + " has been accessed") const url = new URL(req.url) // 临时重定向方案(需替换为正规方案) if (url.pathname.startsWith("/backend/")) { const substring = url.pathname.substring("/backend/".length) console.log("redirect to /"+substring+" from " + url) return Response.redirect("/"+substring, 302); } // Return 404 for unmatched routes return new Response("Not Found", { status: 404 }); }, }); console.log(`Server is running on port ${server.port}`);
正规解决方案
方案1:显式设置bundler的publicPath
通过Bun的导入配置或static选项指定publicPath为根目录/,强制Bun生成基于根路径的资源引用:
- 方法A:修改HTML导入语句
import homepage from "../frontend/index.html" with { type: "html", bundler: { publicPath: "/" } }; - 方法B:在static配置中添加bundler参数
static: { "/": homepage, bundler: { publicPath: "/" } },
方案2:调整服务器工作目录
从repo根目录启动服务器,让Bun的工作目录与项目根目录一致,避免路径计算错误:
- 修改启动命令(进入repo根目录执行):
bun backend/index.ts - 调整index.ts中的HTML导入路径:
import homepage from "./frontend/index.html";
方案3:禁用代码分块
如果不需要分块打包,可以关闭splitting功能,让Bun将所有资源合并为单个文件,彻底避免分块路径问题:
import homepage from "../frontend/index.html" with { type: "html", bundler: { splitting: false } };
临时方案的弊端
当前使用的302重定向方案会额外增加请求开销,且属于路径错误后的补救措施,不如上述正规方案直接从根源解决问题。
内容的提问来源于stack exchange,提问作者redcast
相关产品推荐
相关产品推荐

