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);
});
You need to compile your code using Babel. Check out the docs from their website.
Install
babel
withnpm install -g babel
then dobabel app.js > compiledApp.js
to compile your ES6 code into ES5 code. You can then runcompiledApp.js
.The runtime
babel/register
is still needed if your want to use some functions of ES6 likeObject.assign
which are not compiled but executed thanks to a polyfill. (Check here for examples and more details)Edit: As said in the comment, you can use the
register
to compile on the fly. But it will compile modules you are requiring after thisregister
. It will hook therequire
function fromnode
. More here. You will still need to compile the file where theregister
or to not use any ES6 in this file.I ran into a similar issue trying to render a react page (.jsx) on the server. I fixed it by putting the snippet below at the top of my server file
make sure you have npm
babel-preset-es2015
andbabel-preset-react
installedAccording to this document you have to use:
Additionally, you have to put .babelrc file in the root of directory from which you start server.
Since Babel 7 use, you can use @babel/register
or
if you're using yarn.
In the code you just include the following line:
In the eve of 2019 we still have no good documentation in JS-related libraries, but, on the other hand, we have StackOverflow for that.
In order to use
babel
on Node.js, you need tonpm install @babel/register @babel/core @babel/preset-env
pre-index.js
with attached contentsnode pre-index
You can use
import
s and other features only inindex.js
and files itimport
s orrequire
s.Since
Babel 6
usebabel-register hook
to make on-the-fly transpilation.First:
Then require it with:
To Convert your
Ecmascript 6
code toecmascript 5
, you must setBabel presets
option with requirebabel-register
Like this:Unlike the answer of @alexander-pustovalov you do not need to
.babelrc
file.you must also install
babel-preset-es2015
:Finally your Server.js file will be: