skip to Main Content

I want to create a PM2 process to run my react app, (if a do a serve -s build it will stop working once I disconnect from instance) but getting this error already tried to rename the main but not working

0|citas | }
0|citas | Error [ERR_REQUIRE_ESM]: require() of ES Module /usr/local/lib/node_modules/serve/build/main.js not supported.
0|citas | main.js is treated as an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which declares all .js files in that package scope as ES modules.
0|citas | Instead rename main.js to end in .cjs, change the requiring code to use dynamic import() which is available in all CommonJS modules, or change "type": "module" to "type": "commonjs" in /usr/local/lib/node_modules/serve/package.json to treat all .js files as CommonJS (using .mjs for all ES modules instead).

I tried to rename this /usr/local/lib/node_modules/serve/build/main.js but did not work

2

Answers


  1. To run your React app with PM2 and resolve the ESM/CommonJS compatibility issue,

    Create a pm2.config.js file

    set "type" in your project’s package.json to "commonjs".

    Then, start your app with PM2 using

    pm2 start pm2.config.js
    
    Login or Signup to reply.
  2. It seems like you are encountering issue when trying to your react app with PM2, and you also tried to rename the main file. Here, you should follow some steps:

    npm install pm2 -g
    

    In your react app’s root directory create a PM2 configuration file named pm2.config.js or pm2.json

    {
      "apps": [
        {
          "name": "my-react-app",
          "script": "node_modules/react-scripts/scripts/start.js",
          "cwd": "./",
          "args": "start",
          "exec_mode": "fork",
          "env": {
            "NODE_ENV": "production"
          }
        }
      ]
    }
    • "name" is the name you want to give to your PM2 process.
    • "script" specifies the script that will start your React app. It’s set to start.js from the react-scripts package.
    • "cwd" specifies the current working directory.
    • "args" passes the command-line argument "start" to the script.
    • "exec_mode" is set to "fork" for running in fork mode.
    • "env" sets the NODE_ENV environment variable to "production" to run your app in production mode.

    Then run the command

    pm2 start pm2.json
    

    replace p2.json with your configuration file name

    To check the process status:

    pm2 list
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search