Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use babel-node with pm2

I want to manage my node process with pm2 package. If I don't have any es6 syntax in my code so I don't need to add babel-node, and without any es6 syntax code is am able to run my code with pm2 with this line of code

pm2 start server.js

But as soon as I add any line of code of es6 syntax like this

import express from 'express';

I get the error of unexpected token import.

As you know to solve this issue we have to add babel-node package.

But when I use this line of command to compile my code

pm2 start server.js --interpreter babel-node

I get this error

Error: spawn babel-node ENOENT
at _errnoException (util.js:1022:11)
at Process.ChildProcess._handle.onexit (internal/child_process.js:190:19)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickDomainCallback (internal/process/next_tick.js:218:9)

The strange thing about this is that if I don't use pm2 and run the code with this line of code

babel-node server.js

Every thing is OK.

like image 426
jsDevia Avatar asked Feb 06 '18 06:02

jsDevia


People also ask

How to install and start Babel CLI in PM2?

## Install the Babel CLI globally: npm install -g babel-cli ## Start pm2 with the Babel CLI binary in watch mode: pm2 start --watch --interpreter babel-cli app.js Or, you can create an other file, which requires the transpiler and your app: // index.js require('babel-register'); require('./app.js');

Why use Babel in Node JS?

It's a popular tool that helps you use the newest features of the JavaScript programming language. Why use Babel in Node.js? Have you ever opened a back end repo built with Node.js/Express – and the very first thing you saw was the ES6 import and export statements along with some other cool ES6 syntax features?

How do I install a Babel module?

To install, we use the command below to install the package: We want to use the --save-dev to install them as dependencies for the development of your module. So once you're done with the installation, create a new file called .babelrc for configuring babel.

How do I manage multiple node applications in PM2?

For Node.js applications, PM2 includes an automatic load balancer that will share all HTTP [s]/Websocket/TCP/UDP connections between each spawned processes. Read more about cluster mode here. You can also create a configuration file, called Ecosystem File, to manage multiple applications.


Video Answer


1 Answers

I've only just started using pm2 and I found this helped.

You have your npm script to run es6 js, something like

{
  ...
  "scripts": {
    "server": "babel-node ./src/server.js"
  },
  ...
}

Then to run that with pm2 you use pm2 start npm -- run server Make sure you have babel-cli installed globally.

like image 137
Moosch Avatar answered Oct 12 '22 12:10

Moosch