如何在Next.js(v14)+Vercel部署中挂载Storybook至/storybook/路径?
针对Next.js 13/14 + Storybook 7.x的Vercel部署方案
下面是适配免费Vercel账户的可行方案,核心是把Storybook构建产物嵌入Next.js的静态资源目录,通过单构建流程完成部署:
1. 修改Storybook构建输出路径
编辑.storybook/main.js,指定构建产物输出到Next.js的public/storybook目录,同时设置Storybook的基础路径为/storybook/:
// .storybook/main.js export default { stories: ['../src/**/*.stories.@(js|jsx|ts|tsx)'], addons: ['@storybook/addon-links', '@storybook/addon-essentials'], core: { builder: '@storybook/builder-webpack5', }, staticDirs: ['../public'], // 指定输出目录到Next的public文件夹 outputDir: '../public/storybook', // 设置Storybook的基础路径,避免资源引用错误 base: '/storybook/', };
2. 配置Next.js的Headers(解决静态资源MIME类型问题)
编辑next.config.js,添加Headers规则确保Storybook的静态资源能被正确识别:
// next.config.js /** @type {import('next').NextConfig} */ const nextConfig = { async headers() { return [ { source: '/storybook/:path*', headers: [ { key: 'Content-Type', value: ({ params }) => { const fileExt = params.path.split('.').pop(); switch (fileExt) { case 'js': return 'application/javascript'; case 'css': return 'text/css'; case 'html': return 'text/html'; case 'png': case 'svg': return 'image/png'; case 'jpg': case 'jpeg': return 'image/jpeg'; default: return 'application/octet-stream'; } }, }, ], }, ]; }, }; export default nextConfig;
Next.js默认会从public目录提供静态文件,所以无需额外rewrites配置,直接访问/storybook/即可加载对应的index.html。
3. 合并构建命令(适配Vercel免费账户)
在package.json中修改构建脚本,让Vercel依次执行Storybook构建和Next.js构建:
{ "scripts": { "build": "npm run build:storybook && npm run build:next", "build:storybook": "storybook build", "build:next": "next build", // 其他脚本... } }
然后在Vercel项目的「构建和开发设置」中,将构建命令设置为npm run build(根据你使用的包管理器调整为yarn build或pnpm build)。
4. 本地测试验证
先执行npm run build完成双构建,再启动Next.js服务:
npm run start
访问http://localhost:3000验证Next.js内容,访问http://localhost:3000/storybook/验证Storybook是否正常加载。
额外注意
- 可以在
.gitignore中添加public/storybook/,避免将构建产物提交到Git仓库,Vercel构建时会自动生成该目录。 - 如果遇到Storybook样式或脚本加载失败,检查
base配置是否正确,确保所有资源路径都带有/storybook/前缀。
内容的提问来源于stack exchange,提问作者thepaperescape
相关产品推荐
相关产品推荐

