SvelteKit Static适配器:构建生产环境时为href添加.html后缀
SvelteKit静态适配器自动添加.html后缀到链接的解决方案
先搞懂trailingSlash的作用
trailingSlash: 'always':每个路由会生成带斜杠的目录(比如/otherPage/),对应静态文件是/otherPage/index.html,依赖服务器自动加载目录下的index.html(你的静态服务器不支持这种模式,不适用)trailingSlash: 'never':路由直接生成.html后缀的文件(比如/otherPage.html),这是适配你的静态服务器需要的文件结构trailingSlash: 'ignore':保留开发时的路由结构,不做统一处理,不适合静态部署场景
具体解决步骤
1. 配置SvelteKit生成.html后缀的静态文件
修改项目根目录的svelte.config.js,设置trailingSlash: 'never':
import adapter from '@sveltejs/adapter-static'; import { vitePreprocess } from '@sveltejs/kit/vite'; /** @type {import('@sveltejs/kit').Config} */ const config = { preprocess: vitePreprocess(), kit: { adapter: adapter(), trailingSlash: 'never' // 关键配置 } }; export default config;
执行npm run build后,每个路由都会生成对应的.html文件(比如otherPage.html),而非目录结构。
2. 让链接自动适配环境添加.html后缀
直接写<a href="/otherPage">在build后仍指向/otherPage,静态服务器无法解析,因此可以创建一个自定义Anchor组件,根据环境自动处理href:
创建src/lib/components/Anchor.svelte:
<script> import { building, browser } from '$app/environment'; export let href = ''; // 生产环境(build后)添加.html后缀,开发环境保持原路径 $: processedHref = (building || (browser && import.meta.env.PROD)) ? href.endsWith('/') ? href.slice(0, -1) + '.html' : href + '.html' : href; </script> <a {processedHref} {...$$restProps}> <slot /> </a>
在项目中用这个组件替代原生<a>标签:
<script> import Anchor from '$lib/components/Anchor.svelte'; </script> <Anchor href="/otherPage">跳转到其他页面</Anchor>
3. 验证效果
npm run dev时,链接保持/otherPage,正常访问开发服务器npm run build后,静态文件中的链接自动变为/otherPage.html,适配你的静态服务器
补充说明
如果不想自定义组件,也可以在页面中通过$app/environment的building或PROD变量手动处理href,但自定义组件的方式更通用,无需重复编写逻辑。
内容的提问来源于stack exchange,提问作者Nik
相关产品推荐
相关产品推荐

