首页 > 解决方案 > 为什么 pm2 忽略了生态系统.config.js 文件中传递给节点的--experimental-modules?

问题描述

这是我的main.js文件:

import Koa from "koa";

const app = new Koa();
app.use(async ctx => ctx.body = "Hello, World!");
app.listen(3000);

这是我的package.json文件:

{
  "type": "module",
  "name": "koa-sandbox",
  "version": "1.0.0",
  "description": "",
  "main": "./src/main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node --experimental-modules ./src/main.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "koa": "^2.7.0"
  }
}

当我通过以下方式启动它时它工作正常npm

npm start

现在我需要通过pm2. 这是我的ecosystem.config.js文件:

module.exports = {
  apps : [{
    name: 'API',
    script: './src/main.js',
    node_args : '--experimental-modules',
    instances: 1,
    autorestart: true,
    watch: true,
    max_memory_restart: '1G',
  }],
};

我开始我的申请:

pm2 start .\ecosystem.config.js

但我看到了结果:

在此处输入图像描述

在日志文件中我看到它:

(node:12696) ExperimentalWarning: The ESM module loader is experimental.
C:\lab\koa-sandbox\src\main.js:1
import Koa from "koa";
       ^^^

SyntaxError: Unexpected identifier
    at Module._compile (internal/modules/cjs/loader.js:720:22)

为什么pm2忽略文件中的--experimental-modules传递给?nodeecosystem.config.js

我在这里看到了类似的问题,但它还没有回答...

标签: javascriptnode.jspm2es6-modules

解决方案


对于使用 esm imports,我正在使用esm 包

index.js例如,您可以在文件中添加一个文件

require = require("esm")(module/*, options*/)
module.exports = require("./main.js")

并修改ecosystem.config.js

module.exports = {
  apps : [{
    name: 'API',
    script: './src/index.js',
    instances: 1,
    autorestart: true,
    watch: true,
    max_memory_restart: '1G',
  }],
};

package.json你不必

"start": "node --experimental-modules ./src/main.js"

该脚本将在没有--experimental-modules.

只是

"start": "node ./src/index.js"

推荐阅读