【问题标题】:run pm2 with ES modules使用 ES 模块运行 pm2
【发布时间】:2022-01-23 18:05:01
【问题描述】:

如何将 pm2 与基于 ES 模块的包结合使用(类型:“模块”) 我在没有任何有用帮助的情况下查看了类似的问题(有人说它在 Windows 上不起作用,但我使用的是 linux)

我总是收到错误:

Error [ERR_REQUIRE_ESM]: require() of ES Module /opt/app/server/lib/src/index.js not supported.
0|any| Instead change the require of index.js in null to a dynamic import() which is available in all CommonJS modules.

我的生态系统.config.js 看起来像:

const os = require('os');
module.exports = {
    apps: [{
        port        : 3000,
        name        : "any",
        script      : "lib/src/index.js",
        watch       : true,           
        instances   : os.cpus().length,
        exec_mode   : 'fork',         
        env: {
            NODE_ENV: "production",
        }
    }]
}

index.js 是一个使用“import”语法的 ES 模块。我如何告诉 pm2 应该使用这种导入方式

【问题讨论】:

    标签: javascript pm2


    【解决方案1】:

    要实现这一点,您可以创建一个中间 CommonJS 模块,该模块从 ESModule 加载您的应用程序。可以使用 commonJs 模块中的import 函数。

    这可能是这样的:

    • ecosystem.config.js
    • lib/src/index.cjsCommonJS 入口点(用于 PM2)。
    • lib/src/index.js ESModule 入口点(适用于 ESM 兼容工具)。
    • lib/src/app.js申请代码。

    ecosystem.config.js:

    const os = require('os');
    module.exports = {
        apps: [{
            port        : 3000,
            name        : "any",
            script      : "lib/src/index.cjs", // ? CommonJS
            watch       : true,           
            instances   : os.cpus().length,
            exec_mode   : 'fork',         
            env: {
                NODE_ENV: "production",
            }
        }]
    }
    

    lib/src/index.js:

    import {app} from './app.js'
    
    app()
    

    lib/src/index.cjs:

    import('./app.js') // ? There is import function available in CommonJS
    .then(({app}) => {
     app()
    })
    

    lib/src/app.js:

    import {hello} from './greet.js'
    
    export function app() {
      console.log(hello('World'))
    }
    

    lib/src/greet.js:

    export function hello(name) {
      return `Hello, ${name}!`
    }
    

    【讨论】:

    • 感谢您的回复。将 CommonJs 入口点与 PM2 一起使用时,是否有一种简单的方法可以在 app.js 中使用 esm import?例如在 app.js -> import {func} from "./other.js"。我还没有尝试过,但我想它会再次出现同样的错误。我明天试试,但也许你知道。
    • 如果导出有效,那么导入也可以。我已经用这种导入更新了示例。
    • 非常感谢。那行得通
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    • 2017-11-21
    • 1970-01-01
    • 2021-09-26
    • 2019-08-13
    • 2019-09-01
    • 2017-12-26
    相关资源
    最近更新 更多