April 19, 2016
Start by creating a simple node application with express
$ npm i express -g
$ express //without options if you want an express app with the default jade templating engine)
$ npm install
$ npm start
Et voila, simple as that to create your express app! Now check out the app.js file. You’ll see that require.js is still used and that the code in there is ES5. Now we will transform our app to ES6 and transform it back to ES5 so express can understand our ‘code of the future’.
From:
var express = require 'express';
to:
import express from 'express';
We will use babel-register to make the ES6 code readable for express. Run the command
$ npm i babel-register -S
This will download babel-register and add this to your dependencies in the package.json file.
Now we need to tell babel-register to transform the code. Open the file ‘bin/www’. This file uses the app.js file and creates and starts up an express HTTP server. Our goal is to transform the codebase to ES5 before the express server starts using the codebase. Change the first part of the code:
var app = require('../app'); var debug = require('debug')('BASE-FOLDER-NAME:server'); var http = require('http');
to this:
compileBackEnd(startExpress);
function compileBackEnd(callback) { require('babel-register')({ ignore: [/node\_modules/, /public/javascripts / ], presets: ['es2015'] }); callback(); };
function startExpress() { var app = require('../app'); var debug = require('debug')('BASE-FOLDER-NAME:server'); var http = require('http'); \* ALL OTHER CODE FROM THIS FILE SHOULD COME HERE \* }
This will allow babel-register to do its work before starting up express. As babel is a generic code transformer platform, you must add a preset to babel, to make sure it transforms the ES6 (or ES2015 code). This could be specified by adding the presets property to the babel-register call:
require('babel-register')({ ignore: [/node\_modules/, /public/javascripts / ], presets: ['es2015'] });
Or by adding a .babelrc file to the root directory of the project which specifies the presets.
$ npm i babel-preset-es2015 -S
$ npm start
Having a problem? Compare your code to my example code on Github. Good luck!
Written by Jonathan Dierckens who lives and works in Ghent, trying to build useful things.