webpack with es6

Webpack with ES6 tutorial for beginners

Webpack is actually the best tool to create web pages. Is the next generation tool after gulp and grunt. For me is really easy to configure and manage and I want to show you how I can make projects with this tool.

Prerequisites

First of all, we need node running on our machines. Open terminal or command line and try if you have installed node.js:

if you have installed you see the version of node, if not you need to install it, we have a little post explaining how to install:

Install Node in Mac OS X

You can clone finished project from github for reference: https://github.com/ebavs/webpack-es6-tutorial

Configure Project

Now we need to initialize and configure basics. Create a project folder on your computer and enter.

Initialise Project

First, we need the basics. We work with node and this tool uses a file called package.json to manage projects and dependencies. To create this file we need to execute npm init command and answer questions.

Install Webpack

Now is time to install webpack. We search to install webpack itself and tool called webpack-dev-server that we will use later.

The –save-dev option means that webpack is installed locally like development dependency in the project. If you want to install globally you can use -g option instead. I prefer local because is changing very fast and I don’t  to leave working if I update globally to the last version.

First Steps and Configs

We create 2 folders. One for our code and another one for transpiled code (transpile is the way of transform one code in other code, for example, we will transform es6 in javascript)

And create an index.js file inside src/ folder with the next easy content.

Create webpack.config.js and add the basic part of configuration:

This is the minimal configuration: we add a conf object with path telling the two important paths. A second area, with module.export tell webpack what file needs to look and what file need to generate.

Then we need to create a command to execute webpack through command line. Open package.json and add “serve” task to scripts area. Scripts area looks like:

“serve” task executes webpack calling webpack.config.js and transpile js to another file.

And now try to run with next command in bash:

We created our bundle.js file. But we haven’t HTML yet and for the test, we need to use node:

 

No, this not a web!

But’s not the point. Why? Because we are developing a web and this not a web. We don’t want a node web application. We want a web. Ok, let’s add HTML basic. Now make an index.html inside src/ folder and add basic html code, we don’t need more:

Install required plugin for this operation.

Open webpack.config.js and then open a new section called plugin adding new html webpack plugin:

You can see HtmlWebpackPlugin Documentation here: https://github.com/jantimon/html-webpack-plugin#configuration

Now we can execute again:

If we look inside dist/ folder we could see two files; index.html and bundle.js. HtmlWebpackPlugin gets js from config, and inject script tag inside html, if you open index.html with the browser and open inspector you should see “I’m alive!” message.

Actually, this is a little project, but don’t want to stop here. This is only the beginning. Let’s continue.

 

Begin to build real web page with webpack

At this point, you have webpack with a little configuration but isn’t real. In a real project, you maybe use Bootstrap or Foundation with jQuery or maybe Angular.  Anyway, also we need to know what we want to do, and I believe that better thing is a TODO list!

For a real and simple todo list, we need some images, fonts, CSS, maybe effects and good code. Good code, actually, means ES6 or ES7. We choose ES6. Then, we have all chosen, let’s do begin.

 

ES6 or ECMAScript 2015

Modern browsers do not understand ES6, we need transpile to old-fashioned javascript. To make this transpilations we use babel. Babel is a library that understands a lot of languages and can transpile to javascript.

Install Babel (you can go to https://babeljs.io/ to see all capabilities, I only choose few for this project):

Now we tell webpack that use babel for transpile, to do that we need to add a modules area with rules config:

Explanation: We are telling that all js files (test property) in src/ folder needs to be loaded with babel-loader.

Now, to be sure that we are writing good and correct code we install a lint loader. Every time we write bad code lint tell us to correct:

And their rule inside modules:

We use enforce to be sure that we are executing eslint before babel. Thes use exclude because not want lint al external module.

Now in our root folder need to create a file called .eslintrc.json with this content:

We are telling that eslint uses airbnb rules. You can install other rules, Google has their:

And change “extends” to “google”, but not our case, Airbnb has good ones, you can inspect their rules: https://github.com/airbnb/javascript

Optional: if you want you can add a task in package.json spripts area to lint only. I think that is not needed but is good to be there:

 

Install dependent libraries

It’s time to install bootstrap and jQuery. These libraries have their package in npm repository. Install it:

See that we used –save and not –save-dev. This is because this two libraries are used in our project and needs to be there in production.

Test jQuery

Now test jQuery. Open index.js from src/ folder and change a little bit, remove console.log and add next lines:

If we transpile and open the browser we can see “I’m alive” in a browser page. Cooooool! we are moving forward, we have a phrase in the browser instead of the inspector.

But for use with Bootstrap we need more config, open webpack.config.js and add a new first line:

Then we tell config that use a new plugin to convert jQuery into a global variable, plugins will be:

if you halt this step, after add bootstrap, you will have an error saying that jQuery is not found.

Configure and test CSS/Bootstrap

Bootstrap is a collection of CSS and JS libraries. Include Bootstrap in our code needs an extra effort, first we install all needed and then I explain what is every module:

Yeah!

  • style-loader: gets our CSS files and inject them inside <style> tags.
  • css-loader: interprets @import and url() from css and resolve them
  • sass-loader (node-sass): gets sass and transpiles to css
  • file-loader: gets a file and return new name with md5 hash. It’s needed by previous loaders.

Open webpack.config.js and add:

Paste this code after babel-loader rule.

ES6 don’t know how to handle and import current css. If you try to import bootstrap CSS directly to index.js you will have an error. To avoid this we make a style.scss and put in src/ folder with next content:

The tilde (~) means that need to look inside the node_modules folder.

And finally we add code to index.js that looks like:

I’ve added new div to see if bootstrap is working. Run npm task …….. And yeees!

happy clapping GIF by Originals

Webpack-dev-server

Now, we have working our base to begin the development, but I don’t want to run webpack every time I made a change in code. For avoid running task every time, we have two options; You can run webpack with –watch , that is good or you can run webpack-dev-server, that is better.

The difference is that –watch option leave webpack executed and run every time that rode is changed. It’s ok, but we need more powerful because we are developing web, and debug javascript, then is better a web server. With webpack-dev-server you will have a real web-server integrated with webpack. We installed with webpack, the only want we need changes configuration. Open package.json and change server option:

Then if you run:

You will see all compilations, listings and then ready to browse: http://localhost:8080/

Changing webpack-dev-server configuration

Alternatively, you can change some parameters of web server adding some parameters in webpack.config.js:

Adding devServer to config we can change the port, I prefer 3000 instead 8080.

You can see all options here: https://webpack.js.org/configuration/dev-server/

 

Developing Project

We have now the project with a good base. Let’s begin to create our real todo application.

Making Views

ES6 have one important feature, have templating. You can store HTML in a variable and then inject later in our web page.

Make new views.js in src/ folder. We put inside the little templates for creating page:

We have here to constants with a little bit of HTML. First one constant is the container. The second one is input text box where we will write tasks.

After definition, we add to an object collection and use export to say ES6 that we can use in other files.

Then we can open style.scss file and add some css to separate box to the top of the page:

 

Making Controller

Now we make the controller, create a file called controller.js.  Thi file will be responsible to load views and manage events and data.

It’s time to make with a few lines, only for initialize and show data to the browser:

Then we have a constructor that receive jQuery and views and store them in properties. Then you have initViews method that initializes HTML and injects to DOM via jQuery. Then you have bindEvents to bind events to DOM and start method that calls previous methods.

Put it all working

We have two files (views and controllers) but aren’t called yet. Then open index.js and will see like this code:

Import jQuery and bootstrap and styles and then import views and Controller and call it. Simple. If you browse now you will see the first approach to our ToDo List.

First todo test

Isn’t working yet. But we will go to our final steps!

 

Making all working

We have the base. It’s time to finish this little project coding final events. We don’t want to extend more, don’t store todos in any place. Simply add and remove. Let’s do it!

Adding to Views

Into views, we have only brand and input text. We need list items and todo items. Add next lines to view.js to add new views:

And now change viewCollection constant to add new elements:

Cool, we have now all view parts ready.

Finishing Controller

The controller has the simple binding, addItem method is empty and is static. We need to code all of this. But, first of all, we need to finish initViews because we want to inject item list on the page:

We have now list rendered on the page. Time to code addItem method, but for code, we need to change the constructor to create an item list to store our todos:

And:

Note that we are calling removeItem, create it:

And bindEvents changed to; we need to change call to addItem because isn’t static;

You can run the project and see that all are working as expected. If not, please, feel free to comment any errors you have and I will help you to make this working.

ebavs todo tutorial working

 

Webpack config for debugging

If you browse project and open web inspector you will notice that is impossible to debug project because the code is hidden inside webpack envelope.  If you try to look variable values or do some debug you will enter in a full head pain!

To avoid this situation and serve correct code to chrome we need to add an option to our webpack.config.js :

The devtool  option allows saying webpack and webpack-dev-server that we need to use source map to our code. If you browse project you will notice that can search files with CMD + P (Ctrl+P) and add breakpoints, etc …ebavs webpack debugging

 

Final Words

In a real-world project is probable that you don’t use jquery and bootstrap in a project. Actually are other cool tools you can use in your project like underscore, lodash or some others instead of jquery.

For me, include jquery in this project was a real pain because isn’t prepared for modern life projects. jQuery was created to make easy life to create simple projects and project with ES6  and Webpack are other words.

The same for bootstrap. On EBAVS/ bootstrap are changed to other CSS templates like foundation or skeleton. Bootstrap it’s a big project and sometimes we only need the grid and some helper functions to develop a single project. Bootstrap is a little monster now with a lot of components that we don’t use.

You can clone project from github: https://github.com/ebavs/webpack-es6-tutorial

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *