My Blog

Webpack Core Concepts

May 02, 2020

Webpack is a module bundler that allows developers to write in any module format and compiles them into a artifacts that can be used in a browser. Webpack supports static async bundling (code splitting) helps to optimize the code at build time for high performance.

Github Link: https://github.com/webpack/webpack

https://webpack.js.org/

Before explaining the core concepts, it’s important to understand how webpack can be used. There are 3 ways to use webpack

  1. Webpack Config (webpack.config.js) The config file is a CommonJS module.
  2. Webpack CLI. webpack <entry.js> <output.js> --colors --progress webpack-dev-server --port=9000
  3. Node API

        var webpack = require("webpack");
    
        webpack({
            //configuration object
        }, function(error, status){
            //compiler callbacks
        })

Here are the 4 core concepts in webpack.

  1. Entry. This is the top level application file, from which weback creates the source map. Your application file may import other components such as other modules, sass, css, images. Webpack trace through them and create a source map.

        module.exports = {
            entry: './index.js', //relative path
        }
  2. Output. This object tells webpack how to distribute the files after compilation.

        module.exports = {
            entry: './index.js', //relative path
            output: { //compilations, how to distribute
                path: './dist',
                filename: './bundle.js'
            }
        }
  3. Loaders. Tells webpack how to modify files before its added to dependency graph. Loaders are also JS modules(functions) that takes the source files and returns it in a [modified] state Tells webpack how to interpret and tranlate files. per fiile basis.

        module: {
        rules: [
        {test: /\.ts\$/, use: 'ts-loader'}, //matches the regex - which file to run the loader against
    
                {test: /\.js$/, use: 'babel-loader'},
    
                {
                    test: /\.css$/, use: 'css-loader',
                    use: (Array|String|Function), // that returns loader objects
                    include: RegExp[],
                    exclude: RegExp[], //ignore file .. say for eg: spec files in prod build
                    issuer: (RegExp| String)[],
                    enforce: "pre"|"post" // tells webpack when to run the rule, before or after all othe rules
                    oneof or anyof to ensure only one gets applied, by default all rules are matched
                }
                {
                    test: /\.css$/, use: 'css-loader',
                    use: ['style','css','less']  //chaining loaders. read it like style(css(less())), which means executed from right to left
                }
    
            ],
        }
  4. Plugins

A plugin is an instance(ES5 class) or object with apply property. It allows you to hook into the entire compilation lifecycle Webpack has a varitey of built in plugins. Compiler emit events and plugins are used to add additional functionality to compilations(optimized bundled modules), which loaders can’t do. Plugns are the powerful feature of webpack with access to Compiler API. It does everything else you’d ever want to in webpack.

        function BellOnBundlerErrorPlugin(){}
        BellOnBundlerErrorPlugin.prototype.apply = function(compiler){
            if(typeof(process) !== 'undefined'){
                compiler.plugin('done', function(stats){
                    if(stats.hasErrors()){
                        process.stderr.write('\x07');
                    }
                });
                compiler.plugin('failed', function(err){
                    process.stderr.write('\x07');
                });
            }
        }
        module.exports = BellOnBundlerErrorPlugin;

         //require() from node_modules or webpack or local file
         var BellOnBundlerErrorPlugin = require('bell-on-error')
         var webpack = require('webpack');

         module.exports = {
             plugins: [
                new BellOnBundlerErrorPlugin(), //add new instance of the plugin into plugins key in config object
                                                // provide additional info for arguments
                new webpack.optimize.CommonsChunkPlugin('vendors')
             ]
         }

Webpack follows an event driven architecture and by itself is build using plugins


© 2020, Arun Abraham Home