Webpack is a powerful tool for bundling modules, helping you to organize your code, bundling it in a single js file.
Today, I’m going to create a simple project with webpack. My goal here is to show how to organize Js modules using this tool. Let’s get to it!
First, let’s install webpack globally. (You also need Node and Npm installed).
This is the folder structure of our project:
The app file requires the module1 and module2.
In the index.html, we just include the bundle.js file. Webpack will compile the modules in this file.
This is the webpack configuration. Basically, we are saying to webpack where our entry file is and the bundle filename.
Now we can run webpack:
It will compile our modules and create a bundle.js file. Open the index.html file in your browser to see the result.
In order to serve the static files compiled by webpack, we can use the webpack-dev-server. It automatically updates the browser page when a bundle is recompiled.
Let’s install it:
Now we just run:
Now open: http://localhost:8080/ to see the result.
Let’s say that we need a external module in our project, Jquery for example.
First, let’s install jquery using npm:
Then we just import and use!
You could see how is easy to organize a project in modules using webpack. This is just a simple example, we can do a lot of other things with this tool, like uglyfy, minify, compress static assets, etc.
In the next post, we will use Webpack with Angular2, and build a web application!
You can learn more about webpack here: https://webpack.github.io/
That’s it for today!
I hope you enjoyed! Until next time!