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

Introduction

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.

The generated bundle

I won’t copy the content of bundle.js as it’s quite long so it’s best if you open it in an editor. The code is quite difficult to follow and most of it deals with module caching and making the code work in various browsers. The most interesting section for us is the two functions listed in an array at the end of the file:

([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils__ = __webpack_require__(1);


let myGreeting = Object(__WEBPACK_IMPORTED_MODULE_0__utils__["a" /* default */])('John', 'Smith')
console.log(myGreeting)

/***/ }),
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
const greeting = (firstName, lastName ) => `Welcome to webpack ${firstName} ${lastName}`

/* harmony default export */ __webpack_exports__["a"] = (greeting);

/***/ })
/******/ ]);

We see a list of two functions which correspond to our index.js and utils.js. You’ll recognise at least some code like “let myGreeting”, the call upon logging to the console, you’ll also see the greeting function. The functions are also indexed in the comments with 0 and 1 which of course denote their position in the array of functions. The call…

var __WEBPACK_IMPORTED_MODULE_0__utils__ = __webpack_require__(1);

…imports the module at position 1 from the array which is our greeting function in utils.js to a variable called “__WEBPACK_IMPORTED_MODULE_0__utils__”. Then here…

let myGreeting = Object(__WEBPACK_IMPORTED_MODULE_0__utils__["a" /* default */])('John', 'Smith')
console.log(myGreeting)

…the greeting function is executed with the two input parameters and the result is logged to the console.

The main point here is that webpack successfully found the dependency graph of our JS modules and ordered them in an array. The functions are invoked using index numbers and are also cached.

Code execution

Now let’s build a simple HTML page and see how to run bundle.js in a browser. Add a file called index.html to the project root:

Add index html page to webpack NPM demo project in visual studio code

Here’s the content of index.html that will execute the script upon page load:

<!DOCTYPE html>
<html>
<head>
    <title>Webpack 2 Demo</title>
</head>

<body>
    <h1>Welcome to webpack 2!</h1>
    <script src="build/bundle.js"></script>
</body>
</html>

You can open this file directly in a web browser. On Windows you can just double-click on the HTML file in the file explorer. In order to see the output from bundle.js we need to open the developer tools whose shortcut key is F12 on Edge, Firefox and Chrome. I have the following versions of each at the time of writing this post:

  • FF 53
  • Chrome 60
  • MS Edge 40

The dev tools of all three browsers all have a Console section which should show the console output.

Chrome:

Google Chrome showing the console output of webpack generated file

FF:

Firefox showing the console output of webpack generated file

Edge:

Edge showing the console output of webpack generated file

So all three browsers were capable to run at least some new features of ES6 code, that’s really good. However, if I test the same page in IE 11 then code execution will fail:

Internet explorer choking on webpack generated javascript file

We can safely assume that older versions of FF and Chrome will also choke on the new JavaScript features. IE points at the following line of code:

const greeting = (firstName, lastName ) => `Welcome to webpack ${firstName} ${lastName}`

No wonder it didn’t like that. We’ll get back to this point in a bit.

We’ve made great progress I think. We managed to set up NPM and webpack, configure webpack with a configuration file, make it create a single file out of two JS files and show the result in a browser. If you read through the posts up this point you’ll see that it didn’t actually take much effort to get here if you filter out the textual explanations. We’re at sort of a “Hello world” level of introduction into webpack right now which we can build upon in the upcoming posts.

Coming back to the ES6 syntax problem, didn’t we mention in the beginning of the series that webpack can also transform ES6 features to ES5 for older browsers? Well, yes and no. Remember that by default the main goal of webpack is to create bundled scripts, not more, not less. If we want it to perform other tasks then we have add the correct plugins and declare them in the webpack configuration file.

We’ll see an example in the next post where we add a tool called babel.js which is actually responsible for the ES6 -> ES5 transformation.

View all posts related to JavaScript here.

Advertisements

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

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

  1. alirezanotes says:

    Thanks, but when I use Chrome Version 60.0.3112.113 (Official Build) (64-bit), in Console I see Welcome to webpack ${firstName} ${lastName} instead of Welcome to webpack John Smith. I do not see any errors.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

My goal with this blog is to offend everyone in the world at least once with my words… so no one has a reason to have a heightened sense of themselves. We are all ignorant, we are all found wanting, we are all bad people sometimes.

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: