webpack
is a flexible bundler that provide you with tons of options and configuration so you can personalize your JavaScript projects, but with great power comes a great mess... err, I mean, great responsibility when configuring.In this article I assume you know what
webpack
is, if not please check their great documentation. Also the code portrayed is run in Linux, but everything works similar in other GNU/Linux distros or Mac, to use in Windows you have to make some little configurations, mostly just install a good terminal and npm
. If you found some error don't hesitate to comment or communicate with me. Well, let's go!webpack
Webpack is used primarily to mix and match javascript code. You have code organized in several folders with some (or lot) of external packages, and you want this code to not block the webpage when a user request the page. Using
webpack
you can organize your code better by specify entry-points, ouput and which and when to load what. When you have a large (or growing) code-base, this order is crucial.webpack
helps you to organize all of them using plugins. The idea behind plugins is that you use only the functionalities you need. Also you can choose what will happen to each thing, for example if you want to use a CSS preprocessor or if you want to use chunks for code split.webpack
configuration template. Now we will consider some cases for setup webpack.
in this setup you won't care about HTML or CSS or assets, just in making one or more JS modules to compile.
First step is to create a folder, then inside we initialize
npm
:npm init -y
npm i -D webpack webpack-cli
If you will only need one output JS file the only remaining thing to make is a folder called
src/
and inside a file called index.js
. Inside of this file you can put you code, call other files and import CSS. Now please open your file called package.json
and in the section called "scripts" like this:"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack"
},
All that code will be output into a new file inside
dist/
folder just using this command:npm start
You'll notice the new folder and a file called
main.js
will be produced. This file have already minified and uglyfy code, ready for copy/paste in your HTML! I prepared a GitHub repository here so you can check how the code looks like.