require('babel/register') doesn't work

Kosmetika picture Kosmetika · Mar 23, 2015 · Viewed 48k times · Source

I have isomorphic app written in ES6 on client with Babel transpiler. I want my express server to have the same ES6 syntax as client code.

Unfortunately require('babel/register') doesn't work..

server.js

require('babel/register'); // doesn't work
// require('babel-core/register); doesn't work..

const env = process.env.NODE_ENV || 'development';
const port = process.env.NODE_PORT || 1995;

const http = require('http');
const express = require('express');
const address = require('network-address');

let app = express();

app.set('port', port);
app.use(express.static(path.join(__dirname, 'public')));

app.get('*', (req, res) => {
   res.send('Hello!');
});

http.createServer(app).listen(app.get('port'), function () {
   console.info('Demo app is listening on "%s:%s" env="%s"', address(), app.get('port'), env);
});

Answer

ahmed hamdy picture ahmed hamdy · Jan 25, 2016

Since Babel 6 use babel-register hook to make on-the-fly transpilation.

First:

 npm install babel-register

Then require it with:

require('babel-register');    
// not using 
// require('babel/register');
// or 
// require('babel-core/register);

To Convert your Ecmascript 6 code to ecmascript 5, you must set Babel presets option with require babel-register Like this:

require('babel-register')({
  presets: [ 'es2015' ]
});

Unlike the answer of @alexander-pustovalov you do not need to .babelrc file.

you must also install babel-preset-es2015:

npm install babel-preset-es2015

Finally your Server.js file will be:

require('babel-register')({
   presets: [ 'es2015' ]
});

const env = process.env.NODE_ENV || 'development';
const port = process.env.NODE_PORT || 1995;

const http = require('http');
const express = require('express');
const address = require('network-address');

let app = express();

app.set('port', port);
app.use(express.static(path.join(__dirname, 'public')));

app.get('*', (req, res) => {
   res.send('Hello!');
});

http.createServer(app).listen(app.get('port'), function () {
   console.info('Demo app is listening on "%s:%s" env="%s"', address(), app.get('port'), env);
});