babel-register is a library or rather plugin that transpile the ES6+ based javascript source files into ES5 on runtime (on the fly).
babel-register is a require hook, that will bind node’s require method and automatically transpile the file on the fly. This is not meant for production! It’s considered as a bad practice to compile the code this way. It’s far better to compile the code before deploying.
However this works quite well for development purposes.
Let’s install babel-register first:
npm install babel-register --save-dev
Create a simple index.js file:
console.log('Hello World');
Now create a sample.js file and require index.js and babel-register:
require('babel-register'); require('index.js');
When you run the code using node sample.js you will see the output of index.js – “Hello World”.
node sample.js
Note: You can’t require (babel-register) in the same file that you want to compile, because Node is executing the file before Babel’s transpile.
Is it safe to use babel-register in production?
No. this can be used only for development purposes. If the babel-register is used in the production environment, there may be performance and latency related issues. This is because, the source file will be transpiled on the fly and it may take considerable amount of time for the transpilation process. In order to avoid such issues, you have to use a compiled (or rather transpiled) javascript file for the production environment.