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);
});
require('babel/register')
doesn't transpile the file it is called from. If you want server.js to be included in on-the-fly transpilation, you should execute it withbabel-node
(Babel's CLI replacement fornode
).See my answer here for an example.
steps to fix this:
require('babel/register');
from server.jsin start.js,
require('babel/register'); module.exports = require('./server.js');
The result is that all code inside server.js will be transpiled on the fly by the register. Please make sure you have configured babel correctly with a .babelrc having the content like below