本文已参与「新人创作礼」活动,一起开启掘金创作之路。
前情提要:vue3+vite2的项目,部署在了云服务上,nginx配置大致如下:
server {
server_name my_domain;
location / {
root /home/my_name/frontend/my_project/dist;
try_files $uri $uri/ /index.html;
}
}
本机已配置了服务器的ssh免密码登录
现在想定制一个命令,以便执行yarn fab就可以一键部署最新代码到服务器上
- 脚本内容如下(文件名为
.fab.mjs):
#!/usr/bin/env zx
/**
* * 自动部署脚本 *
* 1. ts检查通过之后`vite build`
* 2. 通过scp将该文件夹传输到服务器
*
* */
// https://github.com/google/zx
import 'zx/globals'
import { echo } from 'zx/experimental'
echo(chalk.blue('Ice cream is the best snack in the north winter.'))
const dist = 'dist'
const user = 'my_name'
const host = 'my_domain'
const project = path.basename(__dirname)
await $`run-s build && scp -r ${dist} ${user}@{host}:~/frontend/{project}/`
- 安装
npm-run-all(该库可以一次执行多个scripts里的命令,用它主要是为了解决本机上有的项目用的是yarn,有的项目用的是pnpm,切来切去容易搞混的问题)和zx(该库可以简化命令语句调用)
yarn add -D npm-run-all zx
- 修改package.json
{
"scripts": {
"dev": "vite --host",
"build:tsc": "vue-tsc --noEmit --skipLibCheck",
"build:do": "vite build",
"build": "run-s build:tsc build:do",
"fab": "zx .fab.mjs",
...
注:该项目是用pnpm的,但是使用npm-run-all之后,只有在add、remove增删包时,必须用pnpm,其他命令都可以yarn/pnpm混用
- 附: 过程中,遇到这样一个错误:
% pnpm add -D npm-run-all :( 1 22-04-23 - 15:24:33
ERR_PNPM_REGISTRIES_MISMATCH This modules directory was created using the following registries configuration: {"default":"http://mirrors.cloud.tencent.com/npm/"}. The current configuration is {"default":"http://registry.npm.taobao.org/"}. To recreate the modules directory using the new settings, run "pnpm install".
这样解决的:
pnpm config set registry http://mirrors.cloud.tencent.com/npm/
- 题外话: pnpm真的是快很多,而且即使是用pnpm创建的项目,也可以用yarn dev来启动服务,用yarn build来打包,用yarn lint来格式化代码,所以用起来还是挺舒服的。
不过由于pnpm的github仓上README文件里,放了一些与技术无关的内容,所以暂时只会把它用于个人项目。