Sign up for Digital Ocean VPS and get $10 credit FREE!

Getting started with WebPack Dev Server (with ES6)

Source Code

Lately, Webpack is making noise around the web, especially in the React community.  In this tutorial, we’ll go over what Webpack is and how we can use it to create a super light weight, yet powerful Javascript boilerplate.

What is Webpack?

Webpack takes modules with dependencies and generates static assets representing those modules.  What does this mean in plain english?  It means that Webpack will figure out the dependencies of your javascript source and pack them together in a nice and clean way. Webpack also has a wide variety of plugins that can perform common code optimizations such as minification (js and css), transpilation (babel), auto base 64 image conversion, and much much more!

Installing Webpack

Make sure you have Nodejs and NPM installed on your local computer.  We need to install Webpack from NPM, you can either install it locally or as a global module:

npm install webpack -g

Next you should create package.json file or clone the demo package.json from our code repository 

{
  "name": "webpack-boilerplate",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "css-loader": "^0.15.6",
    "extract-text-webpack-plugin": "^0.8.2",
    "http-server": "^0.8.0",
    "node-sass": "^3.2.0",
    "sass-loader": "^1.0.3",
    "style-loader": "^0.12.3",
    "webpack-dev-server": "^1.10.1"
  },
  "devDependencies": {
    "babel-core": "^5.8.20",
    "babel-loader": "^5.3.2"
  }
}

We’ll be using various loaders for webpack. Loaders are things webpack use to transform resources into javascript.  Some of the loaders we’ll be using in this tutorial are css loader, sass loader, and babel loader.

We’ll also be installing a webpack dev server, which will act as our localhost server that listens to our resources and hot load on the fly (more on that later).

server.js

var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config');

new WebpackDevServer(webpack(config), {
	publicPath: config.output.publicPath,
	hot: true,
	historyApiFallback: true
}).listen(1337, 'localhost', function (err, result) {
	if (err) {
		console.log(err);
	}

	console.log('Listening at localhost:1337');
});

server.js will start a webpack dev server with configs from webpack.config, enables hot reload and listens to requests at port 1337.

webpack.config.js

var path = require('path');
var webpack = require('webpack');

module.exports = {
    entry: [
        'webpack-dev-server/client?http://localhost:1337',
        'webpack/hot/dev-server',
        './src/scripts/index'
    ],
    output: {
        path: __dirname,
        filename: 'bundle.js',
        publicPath: '/static/'
    },
    module: {
        loaders: [
            { test: /\.js$/, loaders: ['babel'], include: path.join(__dirname, 'src') },
            { test: /\.scss$/, loader: 'style-loader!css-loader!sass-loader?sourceMap', include: path.join(__dirname, 'src/scss')},
            { test: /\.css$/, loader: 'style-loader!css-loader?sourceMap', include: path.join(__dirname, 'src/scss')},
        ]
    },
    plugins: [
            new webpack.HotModuleReplacementPlugin(),
            new webpack.NoErrorsPlugin()
    ]
};

We tell Webpack a few entry points to start it’s recursive bundling, in this case it’s our hot reload dev server and our source code index located at: src/scripts/index.js

The output section tells Webpack where to put the bundled js file.

the Module section is the most important part of this config script.  Here we want to load several loaders for webpack to run its transformations through.  As an example:

{ test: /\.js$/, loaders: ['babel'], include: path.join(__dirname, 'src') },

will tell Webpack to look for all files with .js extension, run it through babel loader, which transforms ES6 (or Javascript 2015) code to ES5 compatible code via Babel, this means you can start writing ES6 code today!

Plugins

Plugins are various webpack related plugins that enable magical things like hot reload (more on that later).

index.js

Since our entry point starts at src/scripts/index.js, let’s look at what it contains:

//CommonJs style import
var greet = require('./greet');

//Es6 module style import
import sum from './sum';

//Scss entry point
require('../scss/base.scss');

console.log('Index Loaded, the sum is', sum);
alert(greet);

What’s great about this is that Webpack with Babel loader allows you to include scripts in javascript in two styles, CommonJS and ES6 imports.

The Sass loader will allow you to include sass files and treat it like any other javascript.

Our code will set the variable greet to the value exported from greet.js:

module.exports = 'Greetings from greet.js';

which contains one line using Common JS format of exporting a value.

and if we look at sum.js

import add from './add';

let sum = add(5, 4);

export default sum = sum;

It imports add function from add.js using ES6 imports and sets sum to equal to the result of add(5,4) and export it as the default value of this module. This way we can output the value of sum from index.js

Lastly, we look at the base.scss file we’ve imported that contains the entry point to our style sheets:

@import 'colors.scss';

html {
	background: $defaultColor;
	color: $textColor;
}

it also imports some colors from colors.scss:

$defaultColor: black;
$textColor: yellow;

You should see a pattern by now, we’re able to modularize our code via imports or includes, and Webpack makes it very easy for us by figuring out all the dependency chain.

Let’s test this, head over to the command line and type in:

npm start

and head over to localhost:1337 and you should see your sample page running.

Hot Module Replacement

Webpack’s Hot Module Replacement is a really cool feature that will speed up your development time.

Hot Module Replacement (HMR) exchanges, adds, or removes modules while an application is running without a page reload.

Comparing this to something like Gulp or Grunt’s Live Reload, this is a step above that, because it will instantly swap out modules that are updated on your page and replace it on the fly, you will be able to retain the state of your page (for example, text inside a text box or a game state). like Magic!

Demo time!

Let’s change greet.js to:

module.exports = 'Hello World';

press save within your favorite code editor and see what happens.  If you did it right, you should notice your browser instantly reloads the greet.js module and updated the alert text to say ‘Hello World‘!

You can hot reload CSS too! Let’s change colors.scss to:

$defaultColor: black;
$textColor: yellow;

press save and you should see your text color changing to yellow on the page.  Cool isn’t it?

That is it for an introduction to Webpack, and we havn’t even cover the full potential of Webpack.   You can learn more about Hot Module Replacement here.  Stick around for more Webpack related tutorials from us in the near future.

If you enjoyed this tutorial, make sure to subscribe to our Youtube Channel and follow us on Twitter @pentacodevids for latest updates!

Related Posts

Webdev News

Loading...
    More News