AppDividend
Latest Web Development Tutorials

Webpack 3 Tutorial From Scratch

Webpack Tutorial For Beginner

2,155

Webpack 3 Tutorial is today’s lesson. Webpack is today’s modern tool to create JavaScript applications. It is the module bundler for advanced Javascript. Webpack builds the graph of the dependencies we are using in our applications that include every module that needs your application. 

Webpack

Webpack divides our dependencies into small bundles and then combine it into the one bundle file depending on our webpack config object, and then this file will be served by our server. So no more request call for our dependencies, just one bundle JavaScript file is needed. That is the big advantage of webpack.



Webpack 3 Tutorial

The configuration of our webpack module is straightforward. You just need to understand the four concepts of the webpack.config.js file. This file exports our webpack configuration object.

  1. Entry
  2. Output
  3. Loaders
  4. Plugins

Entry

It is the entry point of our dependencies graph. Webpack starts and follows the graph dependencies to know what needs to bundle. It follows the graph dependencies nodes and bundles them one by one. Entry file is the kick starter file for our application, and in this file, all of our dependencies are included either directly or indirectly. So in the process of compilation, it will find the different dependencies one by one and bundles them accordingly into small chunks, and at the end, it will combine all the modules in one file which is called “bundle.js” file.

 

Webpack 3.5 Tutorial For Beginner

The figure shows you the webpack tree for three different JavaScript Frameworks. In all these frameworks, Webpack doing the same thing, find the first file and then follow the dependencies and chunks into bundles and then combine it. It will search the node by node in the graph and at the end of the graph, create final JS file called bundle.js.

webpack.config.js

// webpack.config.js

module.exports = {
  entry: './path/to/my/entry/file.js'
};
There are multiple ways to declare your entry property that is unique to your application’s needs.

Output

It simply means that how to treat your bundled code. Its main goal is to put the bundled file in a specific directory defined by webpack configuration object.

webpack.config.js

// webpack.config.js

const path = require('path');

module.exports = {
  entry: './path/to/my/entry/file.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'my-first-webpack.bundle.js'
  }
};

I have used Node.js path module to specify the directory in which webpack.config.js file lives. Output path will be resolved at root folder  >>  dist directory. In below structure bundle.js resides in dist folder.

  • Project folder
  • dist
  • bundle.js

Loaders

Webpack itself only understand the JavaScript files. It does not understand any kind of TypeScript, ES6 or ES7,  Vue extension files. It simply read the plain JavaScript files.

But modern JS files are not the plain Javascript files. They are using a superset of JavaScripts. So we need to somehow bundle them together with the help of webpack as well.

For this solution,  we need to include the language specific loaders to include those files in our entry file and then webpack bundles them in one file, otherwise, at the time of compilation, webpack does not recognize the syntax and then webpack build fails. Webpack treats every file (.css, .html, .scss, .jpg, etc.) as a module.

Loaders in webpack transform these files into modules as they are added to your dependency graph.

At a high level, loaders have two purposes in your webpack config. They work to:

  1. Identify which file or files should be transformed by a certain Loader. (test property)
  2. Transform those files so that they can be added to your dependency graph (and eventually your bundle). (use property)

webpack.config.js

Related Posts
1 of 2
// webpack.config.js

const path = require('path');

const config = {
  entry: './path/to/my/entry/file.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'my-first-webpack.bundle.js'
  },
  module: {
    // Special compilation rules
    loaders: [
      {
        // Ask webpack to check: If this file ends with .js, then apply some transforms
        test: /\.js$/,
        // Transform it with babel
        loader: 'babel-loader',
        // don't transform node_modules folder (which don't need to be compiled)
        exclude: /node_modules/,
        include: [
              path.resolve(__dirname, '../src')
            ]
      },
      {
        // Ask webpack to check: If this file ends with .vue, then apply some transforms
        test: /\.vue$/,
        // don't transform node_modules folder (which don't need to be compiled)
        exclude: /(node_modules|bower_components)/,
        // Transform it with vue
      use: {
        loader: 'vue-loader'
      }
    }
  ]
}
};

module.exports = config;

In above examples, I have used two loaders.

  1. babel-loader
  2. vue-loader

babel-loader:  It transforms ES6 code into ES5 code.

vue-loader:  It helps us to write JS code into .vue files.

Loaders are one kind of helpers to get the new features of JavaScript in older browsers.

Plugins

Webpack Plugin system is extremely powerful and customizable.

To use a plugin, you just need to require() and add it to the arrayplugins. Most plugins are customizable via options. Since you can use a plugin multiple times in a config for different purposes, you need to create an instance of it by calling it.

Most plugins are customizable via Options you can use a plugin multiple times in a config for different purposes, you need to create an instance of it by calling it with.new

For example, we have installed one plugin called html-webpack-plugin

npm install html-webpack-plugin --save-dev

Now, we need to include this plugin in our webpack.config.js file and configure it.

// webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin'); //installed via npm
const webpack = require('webpack'); //to access built-in plugins
const path = require('path');

const config = {
  entry: './path/to/my/entry/file.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'my-first-webpack.bundle.js'
  },
  module: {
    rules: [
      { test: /\.txt$/, use: 'raw-loader' }
    ]
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin(),
    new HtmlWebpackPlugin({template: './src/index.html'})
  ]
};

module.exports = config;

Webpack 3 Tutorial With Example

 

 

Step 1: Create package.json file in your project

 

 

npm init

Further, we need to install webpack locally in our project. So type the following command.

npm install webpack --save-dev

The version of webpack is above 3.5.5. So this tutorial is also called webpack 3.5 tutorial from scratch.

Now, create a webpack.config.js file in a project root folder.

// webpack.config.js

const path = require('path');

module.exports = {
  context: path.resolve(__dirname, "src")
}

Here, I have defined the context of our application. I need the path module so, I have required it by common js module pattern and then use it in the config object.

Step 2: Define entry and output files.

First of all, create two new directories in the root folder.

  1. src
  2. dist
// webpack.config.js

const path = require('path');

module.exports = {
  context: path.resolve(__dirname, "src"),
  entry: './main.js',
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: 'bundle.js'
  }
}

Next, we need to create a main.js file in the src directory.

// main.js

module.exports = {
  title: 'webpack 3.5 tutorial from scratch'
}
Here, input directory is src and output directory is dist. All the directories are absolute to the webpack.config.js file.
Finally, switch to the terminal and type the following command.
webpack

It will start the searching from the main.js file and then bundles it and finally output that file as a bundle.js file.

Output bundle.js file.

// bundle.js

/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, {
/******/ 				configurable: false,
/******/ 				enumerable: true,
/******/ 				get: getter
/******/ 			});
/******/ 		}
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {

module.exports = {
  name: 'krunal'
}


/***/ })
/******/ ]);

For more information, please visit https://webpack.js.org/

Further Posts

  1. Beginner’s Guide To Setup ES6 Development Environment

  2. Beginner’s Guide To Setup React V15.4.2 Environment

Leave A Reply

Your email address will not be published.