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!
Installation
First, let’s install webpack globally. (You also need Node and Npm installed).
Project structure
This is the folder structure of our project:
app.js
The app file requires the module1 and module2.
module1.js
module2.js
index.html
In the index.html, we just include the bundle.js file. Webpack will compile the modules in this file.
webpack.config.js
This is the webpack configuration. Basically, we are saying to webpack where our entry file is and the bundle filename.
Compiling
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.
Development Server
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.
External Modules
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!
Conclusion
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!