如何使用pm2 post-deploy处理部署和构建Typescript Node.js项目



我的项目是一个使用ESM用Typescript编写的Node.js Express服务器。

目前,我的部署过程如下:

  • 使用pm2在本地计算机上运行部署脚本
  • 将git-reo的最新更改拉入Ubuntu服务器
  • 服务器运行npm install并构建Typescript Node.js项目
  • 在build/dist目录中运行启动脚本

我必须在服务器上构建应用程序,因为我不会将/dist文件夹推送到我的git repo,而且这个过程取决于删除和克隆我的repo的最新版本。

但由于我使用production标志进行部署,它只安装我的依赖项(而不是devDependencies(。我不得不将依赖关系从devDependencies转移过来,这样我的应用程序就可以在服务器上构建而不会有任何抱怨。

例如,我目前想在我的项目中设置babel,因为我在单元测试ES模块时遇到了麻烦(这是另一次的故事(。但由于我目前的设置,我需要将所有的babel依赖项作为常规依赖项而不是devDependencies来安装。这让我很不安。我似乎找不到适合我的用例的解决方案。

我是不是应该把我的构建文件夹推送到我的git repo中,这样我就可以在不需要构建的情况下运行启动文件了?我真的不喜欢推送我的构建文件夹。

我是否只是继续将一些devDependencies作为常规依赖项,以便在服务器上正确构建?我真的希望在我的dev/正则依赖关系之间有一层分离。现在它变得一团糟。

以下是一些相关的配置文件:

package.json

"scripts": {
"build": "rimraf dist && tsc",
"test": "c8 --all -r html -r text mocha",
"test-watch": "npm run test -- -w",
"dev": "concurrently --kill-others "tsc -w" "pm2-dev start ecosystem.config.cjs"",
"deploy": "pm2 deploy ecosystem.config.cjs production"
}

ecosystem.config.cjs

apps: [
{
name: 'brobot',
script: 'dist/src/index.js',
node_args: '--experimental-specifier-resolution=node',
env: {
NODE_ENV: 'development'
}
}
],
deploy: {
production: {
user: process.env.AWS_USER,
host: process.env.AWS_PUBLIC_IP,
key: process.env.AWS_SSH_KEY,
ref: 'origin/main',
repo: 'git@github.com:somegitrepo',
path: process.env.AWS_EC2_PATH,
node_args: '--experimental-specifier-resolution=node',
env: {
NODE_ENV: 'production'
},
'post-deploy': 'npm install && npm run build && pm2 startOrRestart ecosystem.config.cjs --env production'
}
}

tsconfig.json

{
"compilerOptions": {
"target": "ES6" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */,
"module": "ESNext" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
"sourceMap": true /* Generates corresponding '.map' file. */,
"outDir": "dist" /* Redirect output structure to the directory. */,
/* Strict Type-Checking Options */
"strict": true /* Enable all strict type-checking options. */,
/* Module Resolution Options */
"moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */,
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
"skipLibCheck": true /* Skip type checking of declaration files. */,
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
},
"exclude": ["node_modules"]
}

我真的很想在我的项目中保留pm2,它非常有用。我肯定忽略了一些东西,但我不确定如何最好地处理这个部署后的设置。

这是因为您使用NODE_ENV=production运行npm install。尝试使用npm install --production=false安装依赖项,即使在生产环境中也应该强制安装开发依赖项

最新更新