Why pm2 ignored the --experimental-modules passed to node in the ecosystem.config.js file?

不羁的心 提交于 2020-08-07 08:03:06

问题


This is my main.js file:

import Koa from "koa";

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

This is my package.json file:

{
  "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"
  }
}

It works fine when I launch it via npm:

npm start

Now I need to do the same via pm2. This is my ecosystem.config.jsfile:

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

I start my application:

pm2 start .\ecosystem.config.js

but I see the result:

In log-file I see it:

(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)

Why pm2 ignored the --experimental-modules passed to node in the ecosystem.config.js file?

I saw similar question here but it hasn't answer still...


回答1:


For using esm imports I am using esm package

You can add a file for example index.js and in the file

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

and modify ecosystem.config.js to

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

In the package.json you do not have to

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

The script will run without --experimental-modules.

just

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


来源:https://stackoverflow.com/questions/57382237/why-pm2-ignored-the-experimental-modules-passed-to-node-in-the-ecosystem-confi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!