【问题标题】:Run Typescript application with PM2使用 PM2 运行 Typescript 应用程序
【发布时间】:2019-10-27 05:26:06
【问题描述】:

我有一个用 Typescript 编写的应用程序,它与 PM2 一起运行。目前我编译为 JavaScript,然后使用 PM2 启动应用程序。我的ecosystem.config.js 文件如下所示:

module.exports = {
  apps: [
    {
      name: 'My Application',
      script: './dist/server/index.js',
      env_qa: {
        PORT: 3001,
        NODE_ENV: 'production',
      },
      env_production: {
        PORT: 3000,
        NODE_ENV: 'production',
      },
    },
  ],
};

我使用以下命令运行它:

pm2 stop ecosystem.config.js --env qa

开发时,我只运行ts-node server,而不是编译和使用PM2。我最近读到 ts-node 具有“transpileOnly”或“快速”模式,这意味着它可以在生产中使用。首先,我想知道这是否可以在生产环境中使用。其次,我如何仍然使用 PM2 来启动我的应用程序但使用 ts-node?​​p>

【问题讨论】:

  • @bambam 谢谢,我在发布问题之前确实检查了该链接,但只是想弄清楚一些。
  • 是的,没有回答关于快速模式的问题,但是如何使用 ts-node 运行它......认为它可能会有所帮助
  • 我正在使用pm2 start ts-node -- -P tsconfig.server.json ./server/index.ts
  • @Sabee 谢谢,这对您来说是否有效?与运行已编译的节点代码相比,您是否注意到任何性能问题?

标签: javascript typescript pm2


【解决方案1】:

开发环境

运行时会导致极高的内存消耗和服务器过载,最终无法用于生产,链接https://pm2.io/docs/runtime/integration/transpilers/

  "scripts": {
    "pm2": "NODE_ENV=production pm2 start server.ts --watch"
  }

生产用途

使用单独的命令将 typescript 转换为 javascript,并使用 npm run pm2npm run pm2:staging 如果您有暂存环境。

npm run prodnpm run staging 命令仅在我需要在本地使用生产和暂存环境时在本地使用。

  "scripts": {
    "pm2": "NODE_ENV=production pm2 start build/server.js --watch -i max",
    "pm2:staging": "NODE_ENV=staging pm2 start build/server.js --watch -i max",
    "prod": "NODE_ENV=production node build/server.js",
    "staging": "NODE_ENV=staging node build/server.js",
    "dev": "HTTPS=true NODE_ENV=development ts-node-dev --inspect --respawn src/server.ts",
    "test": "NODE_ENV=test nyc ./node_modules/.bin/mocha --require ts-node/register ./src/test/**/**/**/**/*.test.ts",
    "build": "rimraf build && tsc -p tsconfig.json"
   }

tsconfig.json

{
  "compilerOptions": {
    /* Basic Options */
    "target": "es5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */,
    "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
    "lib": [
      "es2015", "dom"
    ] /* Specify library files to be included in the compilation. */,
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
    "sourceMap": true /* Generates corresponding '.map' file. */,
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    "outDir": "./build" /* Redirect output structure to the directory. */,
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                     /* Enable project compilation */
    // "removeComments": true,                /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true /* Enable all strict type-checking options. */,
    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* Enable strict null checks. */
    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
    "strictPropertyInitialization": false,  /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    "noUnusedLocals": true /* Report errors on unused locals. */,
    "noUnusedParameters": true /* Report errors on unused parameters. */,
    "noImplicitReturns": true /* Report error when not all code paths in function return a value. */,
    "noFallthroughCasesInSwitch": true /* Report errors for fallthrough cases in switch statement. */,

    /* Module Resolution Options */
    "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    "types": ["reflect-metadata"],
    // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */

    /* Source Map Options */
    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    "experimentalDecorators": true,           /* Enables experimental support for ES7 decorators. */
    "emitDecoratorMetadata": true,             /* Enables experimental support for emitting type metadata for decorators. */
    "skipLibCheck": true
  }
}

PM2 可以生成启动脚本并对其进行配置,以使您的进程列表在预期或意外的机器重启时保持完整,这对于保持自动化很重要,链接https://pm2.keymetrics.io/docs/usage/startup/

pm2 unstartup
pm2 startup
pm2 save

【讨论】:

  • 它在该页面上说的第一件事:We highly don’t recommend to use this in production as it slows down your app
  • 同意,我也看到了,但有问题。可能只是停机时间需要转译而没有基准。湾。此外,可能需要在暂存服务器上运行“生产”环境,其中速度问题并不重要。
  • @CaribouCode 需要注意的是,但对于某些应用程序来说,这并不重要。我正在开发一个私人聊天机器人。对于这种情况,处理编译的开发开销是不值得的。
【解决方案2】:

我做了一个简单的解决方案,使用项目根目录下的 pm2 配置文件:

project
│   pm2.config.js
│   package.json  
│   tsconfig.json    
│
└───src
│   │   index.ts
└───dist
    │   index.js

pm2.config.js

module.exports = {
    apps: [
        {
            name: 'My Application',
            script: './dist/index.js',
        },
    ],
};

package.json

"scripts": {
 "dev": "ts-node-dev --respawn --transpile-only ./src/index.ts",
 "start": "tsc && node ./dist/index.js",
 "pm2": "tsc && pm2 start pm2.config.js"
}

注意:如果您愿意,也可以将&& pm2 save 添加到 pm2 脚本中

现在在开发中,输入:npm run dev 在生产中,使用npm run pm2注册到pm2

【讨论】:

    【解决方案3】:

    package.json 脚本应如下所示:

    package.json 文件(包含以下示例脚本)

    "scripts": {
        "shivkumarscript": "ts-node -T -P server/tsconfig.json server/index.ts"
      }
    

    ecosystem.config.json 文件

    module.exports = {
        apps: [
            {
                name: "NodeServer",
                script: "npm",
                automation: false,
                args: "run shivkumarscript",
                env: {
                    NODE_ENV: "development"
                },
                env_production: {
                    NODE_ENV: "production"
                }
            }
        ]
    }
    

    假设你已经在你的机器上安装了 Node.js、NPM 和 PM2。然后下面应该是通过 pm2 启动应用程序的命令,该命令将依次运行 npm 脚本(在应用程序的 package.json 文件中提到的命令行):

    生产环境:

    pm2 start ecosystem.config.js --env production --only NodeServer
    

    对于开发环境:

    pm2 start ecosystem.config.js --only NodeServer
    

    ...还有 Boom!伙计们

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-06
      • 2018-06-03
      • 1970-01-01
      • 2019-06-24
      • 1970-01-01
      • 1970-01-01
      • 2023-01-21
      相关资源
      最近更新 更多