搬瓦工部署 SvelteKit 应用教程
SvelteKit 是 Svelte 框架的全栈应用框架,以编译时优化和极小的运行时著称。Svelte 组件在构建时被编译为高效的原生 JavaScript,无需虚拟 DOM,因此性能极佳。SvelteKit 支持 SSR、SSG 和 SPA 多种渲染模式。本文将介绍如何在搬瓦工 VPS 上部署 SvelteKit 应用。购买搬瓦工 VPS 请参考 全部方案,使用优惠码 NODESEEK2026 可享受 6.77% 的折扣。
一、环境准备
apt update && apt upgrade -y
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt install -y nodejs git
npm install -g pm2
二、创建 SvelteKit 项目
cd /opt
npx sv create myapp
cd myapp
npm install
三、适配器配置
3.1 Node.js 适配器(SSR)
npm install @sveltejs/adapter-node
修改 svelte.config.js:
cat > /opt/myapp/svelte.config.js << 'EOF'
import adapter from '@sveltejs/adapter-node';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
export default {
preprocess: vitePreprocess(),
kit: {
adapter: adapter({
out: 'build',
precompress: true,
envPrefix: ''
})
}
};
EOF
3.2 静态适配器(SSG)
npm install @sveltejs/adapter-static
# 将 adapter-node 替换为 adapter-static
四、构建与运行
npm run build
# SSR 模式使用 PM2 运行
cat > /opt/myapp/ecosystem.config.js << 'EOF'
module.exports = {
apps: [{
name: 'sveltekit-app',
script: './build/index.js',
cwd: '/opt/myapp',
env: {
NODE_ENV: 'production',
PORT: 3000,
HOST: '127.0.0.1'
},
instances: 'max',
exec_mode: 'cluster',
autorestart: true,
max_memory_restart: '300M'
}]
};
EOF
pm2 start ecosystem.config.js
pm2 save
pm2 startup
五、Nginx 反向代理
apt install nginx -y
cat > /etc/nginx/sites-available/sveltekit.conf << 'EOF'
server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /_app/ {
alias /opt/myapp/build/client/_app/;
expires 1y;
add_header Cache-Control "public, immutable";
}
}
EOF
ln -sf /etc/nginx/sites-available/sveltekit.conf /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default
nginx -t && systemctl restart nginx
六、SSL 与自动部署
apt install certbot python3-certbot-nginx -y
certbot --nginx -d yourdomain.com
cat > /opt/myapp/deploy.sh << 'EOF'
#!/bin/bash
cd /opt/myapp
git pull origin main
npm install
npm run build
pm2 restart sveltekit-app
echo "[$(date)] SvelteKit deployed"
EOF
chmod +x /opt/myapp/deploy.sh
七、常见问题
适配器选择
如果站点不需要动态数据,使用 adapter-static 生成纯静态页面,性能更好且无需 Node.js 进程。需要 SSR 功能则使用 adapter-node。
预压缩资源
Node 适配器的 precompress: true 选项会在构建时生成 .gz 和 .br 文件,Nginx 可以直接使用预压缩文件提升性能。
总结
SvelteKit 以极小的包体积和出色的运行时性能著称,是构建高性能 Web 应用的优秀选择。在搬瓦工 VPS 上部署简单高效。其他框架教程包括 Nuxt.js、Remix、Astro 等。购买搬瓦工 VPS 请访问 bwh81.net,使用优惠码 NODESEEK2026 可享受 6.77% 的折扣。