Using webpack 2 and NPM to bundle various resources of a web application part 5: adding babel.js for ES5 transformation


In the previous post we first briefly discussed the output that webpack generates in the bundle.js file. Simply put, webpack extracts the dependency graph from the various JS input files and organises the elements into functions that in turn are placed into an array. The functions in the array are invoked in a sequence that reflects the dependency graph. Then we also built a minimal HTML page to execute the bundle in various browsers. Our ES6 code was successfully executed in all of them except for IE11 which is obviously too old to correctly interpret the new ES6 features. We would see the same in older versions of Chrome and FF as well.

In this post we’ll explore another great feature of webpack, namely the ease at which we can add plug-ins to the bundling process. We’ll specifically add babel.js to transform ES6 code to ES5. The point here is that JS developers want to be able to use the latest and greatest of ES6 and other future versions of JavaScript without having to worry about JS support across various browsers.

Read more of this post


Using webpack 2 and NPM to bundle various resources of a web application part 4: executing the bundle


In the previous post we successfully configured webpack and executed it to create a bundled JS file in the build folder. We saw that the bundle.js file is larger than the two small input JS files together. That’s understandable as the generated bundle contains a lot of configuration code that webpack added on top of the file.

In this post we’ll briefly look at the generated bundle and also create a HTML page to execute bundle.js.

Read more of this post

Using webpack 2 and NPM to bundle various resources of a web application part 3: configuring and executing webpack


In the previous post we started setting up a minimal project for our webpack demo. We installed Node.js so that we can create an NPM project where NPM stands for Node Package Manager. We also installed webpack as a development dependency and discussed the difference between development and production dependencies in an NPM project. We went through the role of the package.json file and saw where the dependencies are installed on disk. Finally we added two JS files to our src folder but left them empty.

In this post we’ll first briefly discuss dependencies between JS modules. Then we’ll go ahead and configure webpack, activate it for our demo project and run it using NPM.

Read more of this post

Building a web service with Node.js in Visual Studio Part 5: npm and Express.js basics


In the previous post we discussed the absolute basics of a Node web application. It really didn’t have a lot of functions: it listened to every single incoming request and responded with some properties of the request. We also come to the conclusion that those functions were quite limited. We have no routes, no controllers, no nothing, so working with code on that level is really cumbersome.

In this post we’ll discuss the package manager of Node i.e. the Node Package Manager npm. We’ll also go through the basics of Express.js which is a web framework built on top of Node.

We’ll build upon the CustomerOrdersApi so have it ready in Visual Studio – or in the IDE of your preference. You can write Node.js in Notepad if you wish, but Visual Studio provides some extras, like debugging, break points, intellisense etc.

Node Package Manager

One element we haven’t discussed so far is the little node called “npm”:

npm node in visual studio

npm stands for Node Package Manager. It is the Node.js equivalent of NuGet in .NET and Maven in Java. It is a tool for managing dependencies that are not part of standard Node.js. E.g. the “http” package we saw previously is included by default so we didn’t have to import it. There are a number of packages that are not installed by default and they need to be imported if you need to use them.

The imported packages will be referenced in the file called package.json, visible in the above screenshot. This function of package.json is similar to pom.xml in a Java Maven project and packages.config in .NET. The dependencies in package.json will be read by the IDE and install the necessary dependencies after opening the project for the first time.

This is valid for Node.js, .NET and Maven as well: it’s not necessary to send the dependencies around to other developers. You can upload the project and package.json to a central source, like SVN or Git. Another developer who downloads it from source control can look into package.json and install the dependencies or let Visual Studio take care of it automatically.

So what external libraries are available? This site lists all of them. Packages are referenced by names such as “grunt”, “express” or “underscore”.

Manual installation

You can call npm in a command prompt. If you open a command prompt and type “npm” then, if you followed the Node.js installation in part 1 then you should get the usage help message of npm:

npm in command window

Close the command prompt, this was just a test to see of “npm” works. Right-click the project name in Visual Studio and click “Open Command Prompt Here”. Enter the following command to install the package called “grunt”:

npm install grunt

If everything goes well then you’ll see that grunt is installed along with all dependencies of grunt:

npm manual install grunt output

The dependencies will be listed under the npm node and stored in a folder called “node_modules”:

grunt visible as dependency in project

However, what’s that “not listed in package json” about? Open package.json and you’ll see nothing about dependencies there, right? This means that you can use grunt in your project but other developers won’t be aware of it just by looking at the package.json file. They will see some reference to it in the code, like request(‘grunt’) and then they’ll need to fetch the dependency via npm themselves.

Let’s uninstall grunt by the following command:

npm uninstall grunt

Grunt will silently disappear from the project.

The –save flag will ensure that package.json is filled in:

npm install grunt –save

Check package.json and you’ll see a field called “dependencies”:

"dependencies": {
"grunt": "^0.4.5"

Uninstall grunt before we continue:

npm uninstall grunt –save

Using the npm tool

There’s a more visual approach to all this. Right-click “npm” in Solution Explorer and select “Install New npm Packages”. This will first load all available packages and then open a window similar to the following:

npm visual tool

Search for “grunt”, click on the package name to select it – the present version of grunt is 0.4.5, you might see something higher – and then click “Install package” leaving all other default values untouched. Grunt will be installed again.

If you right-click npm again then you’ll see options like “Update npm Packages” and “Install Missing npm Packages”. These do exactly what’s expected based on their descriptions: update installed npm packages and install any missing ones based on the package.json file. So another developer who downloads your project can simply run these functions to get the necessary dependencies.

If you right-click the grunt pckage under npm you’ll be able to uninstall it by selecting “Uninstall npm package(s)”.

Installing Express.js

Express.js is a web framework comparable to ASP.NET on top of IIS. It is a dependency that can be downloaded via npm like we did with grunt. Right-click “npm” and select Install New npm Packages. Search for “express” and select the first result that comes up:

ExpressJs package in NPM

By the time you read this post there will almost certainly be an updated package but hopefully there won’t be large code changes. Clicke “Install package” and then Express and its dependencies should be installed:

ExpressJs installed with dependencies

Check package.json as well, “express” should appear in the dependencies array. The node_modules folder was also populated with Express with its own node_modules folder for its dependencies:

ExpressJs in node_modules folder with its dependencies

Using Express.js

Now that we have installed Express.js let’s use it. We’ll go through the statements first and re-write server.js at the end.

The first step is to import Express into our project like we did with “http” using the require method:

var express = require('express');

“express” can be executed like a function and it will return a reference to our application, like in a singleton:

var app = express();

We can take this reference and pass it into the createServer method in place of the current callback. Here’s the current state of server.js:

var http = require('http');
var express = require('express');
var app = express();
var port = process.env.port || 1337;

The application doesn’t do anything yet but this step was necessary to have Express drive our web app.

Express takes care of requests based on the web methods, like GET, POST etc. and the URL. Express exposes methods to handle the HTTP verbs and the methods are named exactly as those verbs: get, post etc. They accept a URL and a callback function which will be similar to what we had before. Add the following code after app = express():

app.get("/", function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end("<html><body><p>Hello from the application root</p></body></html>");

The above code ensures that we respond to GET requests to the root of the web app which is “/”. Run the application and you should see the message in the browser. You can test other URLs, such as /index, they won’t work, you’ll get an exception message on the screen saying like “Cannot GET [url]”.

Notice that we’re sending HTML back whereas RESTful APIs normally respond with JSON. Let’s see how we can respond with Json. Insert the following code after the get method shown above:

app.get("/customers", function (req, res) {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end('{name: "Great customer", orders: "none yet"}');

Run the application and navigate to /customers. You should see the JSON as shown in the code. There’s in fact a more concise way of sending a response using the “send” method:

app.get("/customers", function (req, res) {
    res.set('Content-Type', 'application/json');
    res.send({name: "Great Customer", orders: "none yet"});

The writeHead method was replaced by the set method. Also, note the lack of apostrophes around the JSON object, i.e. we’re not specifying the JSON as a string. Re-run the app to make sure that everything works. You’ll see the JSON object as string in the browser window. In fact we can even leave out the set method in this case and Express will infer from the object type that we’re sending back a JSON object. However, the set method can be used to put other headers types to the response.

In the next post we’ll look at the module.exports function and controller basics.

View all posts related to Node here.

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: