部署
如果你只是简单的部署,你只需要将整个 dist 文件夹复制到你的 CDN 或静态服务器。index.html 应该是你的服务器入口。
前端路由与服务端的结合
如果你遇到 https://cdn.com/users/123 刷新后 404 的问题,你需要按照这个章节进行处理。
Caih Admin Pro 使用的 vue-router 可以使用两种路由方式:browserHistory 和 hashHistory。
可以在 .env 中进行配置选择用哪个方式:
# 默认为history
VITE_HISTORY_MODE = 'hash'具体详情请看 环境变量 章节。
hashHistory 使用如 https://cdn.com/#/users/123 这样的 URL,取井号后面的字符作为路径。browserHistory 则直接使用 https://cdn.com/users/123 这样的 URL。使用 hashHistory 时浏览器访问到的始终都是根目录下 index.html。使用 browserHistory 则需要服务器做好处理 URL 的准备,处理应用启动最初的 / 这样的请求应该没问题,但当用户来回跳转并在 /users/123 刷新时,服务器就会收到来自 /users/123 的请求,这时你需要配置服务器能处理这个 URL 返回正确的 index.html,否则就会出现 404 找不到该页面的情况。强烈推荐使用默认的 browserHistory。
部署到非根目录
部署在非根目录是一种常见的需求,比如部署在 GitHub pages 中。接下来我们假设我们要部署项目到 ${host}/admin 中。首先我们需要在 .env 中配置 VITE_BASE_URL。我们需要将 VITE_BASE_URL 配置为 admin, 设置以后在 /dist/index.html 中的基本路径会以 /admin 开始。
VITE_BASE_URL = '/admin'部署到不同的平台
使用 nginx
nginx 作为最流行的 web 容器之一,配置和使用相当简单,只要简单的配置就能拥有高性能和高可用。推荐使用 nginx 托管。示例配置如下:
server {
listen 80;
# gzip config
gzip on;
gzip_min_length 1k;
gzip_comp_level 9;
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
gzip_vary on;
gzip_disable "MSIE [1-6]\.";
root /usr/share/nginx/html;
location / {
# 用于配合 browserHistory使用
try_files $uri $uri/index.html /index.html;
# 如果有资源,建议使用 https + http2,配合按需加载可以获得更好的体验
# rewrite ^/(.*)$ https://preview.pro.ant.design/$1 permanent;
}
location /api {
proxy_pass http://api.caih.com/;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
}
}
server {
# 如果有资源,建议使用 https + http2,配合按需加载可以获得更好的体验
listen 443 ssl http2 default_server;
# 证书的公私钥
ssl_certificate /path/to/public.crt;
ssl_certificate_key /path/to/private.key;
location / {
# 用于配合 browserHistory使用
try_files $uri $uri/index.html /index.html;
}
location /api {
proxy_pass http://api.caih.com/;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
}
}使用 express
express 的例子:
app.use(express.static(path.join(__dirname, 'build')));
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});使用 egg
egg 的例子:
// controller
exports.index = function* () {
yield this.render('App.jsx', {
context: {
user: this.session.user,
},
});
};
// router
app.get('home', '/*', 'home.index');