Webpack - modern way for frontend configuration

Nowadays frontend professionals have the ability to use a variety of automation systems that accelerate and facilitate work. Gulp, Grunt, Browserify, Brunch, Commonjs, Webpack – these are the basic tools that are used every day by millions of developers all over the world. As they say – a good programmer should be lazy by nature – if he has to repeat something more than once, he will write a script that will do it for him, and in the end will accelerate the work. So, why not use tools that someone has done for us and which will provide us with a number of ready-made automation solutions that we do every day? This is the end of searching for code, downloading, copying and adding more script and link entries in html.

Why Webpack? 1. In a nutshell – it’s easy to set up and has a lot of ready-made solutions. Webpack developers and independent developers carry out to providing us with ready loaders and plugins that can be easily installed using the nmp (the package manager) and easily configured by adding an entry in the configuration file. 2. Managing dependencies. Everyone who is programming in an older version than ES6 knows how hard it is to create ‚nice’ code, to keep order in it, and inject dependencies, such as jQuery or twBootstrap.

Webpack simplifies it all.   jQuery case: Installation through consoles: npm install jquery Load dependencies in code: var $ = require(‘jquery’) ; Quick and easy – without searching for code, downloading, copying and adding anything in html, and when we add the ability to load images, fonts, styles here, we have a comprehensive solution.

How does Webpack work? Webpack’s task is to capture dependencies in the project and create static „packages” with code, that are subsequently loaded on demand. All dependencies defined by require () or import are grouped (which prevents duplication) and folded into one file or copied to another location. Each file, e.g. js, css, sass, txt, jpg, html etc. is treated as a module. After dependencies are loaded, we can process them, which gives us unlimited possibilities of what happens to the data contained in them or with the whole file. For this purpose loaders and plugins are used. Loaders – they allow you to process files before modules are created and merged into a single file. We can, e.g., convert sass on css, es6 on es5, copy fonts and images or other files. Plugins – they allow you to process files before modules are created and merged into a single file. We can, e.g., convert sass on css, es6 on es5, copy fonts and images or other files.

Cases. This article will discuss about basic usage. We need to install nodejs and npm.

1. We initiate a new project and complete the information we are asked for. npm init The package.json, file will be created in place where will be kept e.g. informations about packages we use and scripts, as in other words some kind of aliases. 2. Installation and configuration Global installation npm install webpack -g We add as a development package into the dependencies in our project –save-dev npm install webpack –save-dev We create configuration file:

module.exports = {

               entry: './src/app.js',

      output: {

            path: __dirname,

            filename: 'dist/bundle.js'

      }

};

Simple configuration that allows us only for inject dependencies at the moment. Let’s see, what happens when we install and load jQuery.

Console:npm install jquery –save app.js var $ = require(‚jquery’); We run webpack by typing into console: webpack JQuery will be added to the dependency list in package.json and the code will be merged into one file in bundle.js Simple and pleasant.

Now, let’s see how we can use it practically. A better approach than global loading of dependencies in a entry file is to load it where we intend to use it. This allows us better organize code and gives the image – which is used to handle the component/module. Let’s try to create a service, that will allow you to send forms using ajax. We create a services catalog which contains two files: – index.js in which we will load all the services, – and AjaxForm.js where our class will be located to sending the forms. In app.js, we load all services referencing the index.js file in the services catalog. (If we load our local modules, then we need to use relative paths. Specifying only the name e.g. require(‚AjaxForm’), will cause webpack to look in node_modules. You can actually define this in a configuration file, but that is the topic for the next post. So we should refer to this as – require(‚./AjaxForm’)). Code looks like this:

AjaxForm.js

var $ = require('jquery');
 module.exports = (function () {

/**
 * AjaxForm class to send a form via ajax
 *
 * @param $form
 * @constructor
 */
 function AjaxForm ($form) {
 this.form = $form;
 }

/**
 * Get send method
 *
 * @returns {*|string|string}
 * @private
 */
 AjaxForm.prototype._method = function () {
 return this.form.method || 'post';
 };

/**
 * Get the url for send
 *
 * @returns {string|string}
 * @private
 */
 AjaxForm.prototype._url = function () {
 return this.form.action || '';
 };

/**
 * Get the form data
 *
 * @returns {*}
 * @private
 */
 AjaxForm.prototype._data = function () {
 return new FormData(this.form);
 };

/**
 * Run the send process
 *
 * @returns {*}
 */
 AjaxForm.prototype.send = function () {
 return $.ajax(this._url(), {
 method: this._method(),
 data: this._data(),
 processData: false
 });
 };

return AjaxForm;
 })();

index.js w services

module.exports = {

      ajaxForm: require('./AjaxForm')

};

app.js (webpack entry)

window.services = require('./services');

Usage:

<!DOCTYPE html>

<html lang="en">

<head>

   <meta charset="UTF-8">

   <title>Webpack sample</title>

   <script src="./bundle.js"></script>

</head>

<body>

<script>

   var onSubmit = function ($e, $form) {

       $e.preventDefault();




       var ajaxForm = new services.ajaxForm($form);

       ajaxForm.send();

   }

</script>

<form onsubmit="onSubmit(event, this)" action="test.php" method="post">

   <input type="text" name="name">

   <input type="submit" value="Submit">

</form>

</body>

</html>

In an easy and simply way we could organize our code with full control over where and when it is loaded. We can now e.g. in easy way find the used code and to control its structure. In the next article we will show you, how to even more ‚decorate’ our code by adding babel-loader and ES6.

Worth to read about:

Usage of es6 and watch, and addition the script into package.json using the above.

Styles, copying graphics files and fonts (bootstrap example) by using the above.