You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法运行PM2进程:React应用部署ESM兼容问题求助

解决PM2运行React应用时的ERR_REQUIRE_ESM错误

问题原因

serve 包的 package.json 中声明了 "type": "module",将所有 .js 文件标记为ES模块,但PM2默认以CommonJS模式加载模块,导致require()无法加载ES模块,触发ERR_REQUIRE_ESM错误。直接重命名main.js无效,因为包的模块类型由package.json全局控制,且修改全局node_modules文件会被后续包更新覆盖。

解决方案

方案1:用PM2配置文件直接执行serve命令

在项目根目录创建ecosystem.config.js:

module.exports = {
  apps: [
    {
      name: 'citas',
      script: 'npx',
      args: 'serve -s build',
      autorestart: true,
      watch: false,
      max_memory_restart: '1G',
      env: { NODE_ENV: 'production' }
    }
  ]
};

执行启动命令:

pm2 start ecosystem.config.js

方案2:直接用PM2的exec模式启动

无需配置文件,直接执行:

pm2 start --name citas "npx serve -s build"

方案3:自定义ES模块启动脚本(适合需要自定义逻辑的场景)

创建serve-start.mjs文件:

import { createServer } from 'serve';

const server = createServer({
  port: 3000, // 可自定义端口
  root: './build',
  single: true // 对应-s参数,适配React单页应用路由
});

server.listen(() => {
  console.log('React应用已启动,监听端口3000');
});

用PM2启动该脚本:

pm2 start --name citas serve-start.mjs --interpreter node

内容的提问来源于stack exchange,提问作者Javier Morales

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 22:32:46