Understanding Webpack Configuration – [simplified]

Understanding webpack configuration with example codes is much easier than a detailed paragraph. Recently  Angular [Latest version] also use webpack for bundle the application. You can use webpack with any of the latest  Javascript libraries like react to bundle the application.

Here I add webpack configuration file and explain the concept and configuration behind that. Before that, I start with small heads up on webpack.

webpack configuration

Webpack is a module bundler for the modern javascript application, which bundles all the dependencies required by the application. Unlike Grunt or Gulp, This will process your application and build the dependency graph and make those dependencies into a smaller bundle. Finally, this gives a processed bundles as javascript which needs to be loaded by the application.

Webpack Configuration 

All the configuration are object available under the module.exports object.

module.exports = {
....
}

There are four important basic key configurations in webpack

Entry:

Configuration options determine the entry point dependency graph of the module bundle.

Output:

configuration options determine the output bundle path and its name.

Module Loaders :

As webpack only understand Javascript all the assets need to be bundled inside the webpack. These loader and rules are responsible for those actions.

Plugins :

This adds custom functionality to the modules at compilation. Most of the plugins have customization via options parameter.

In the below code snippet, I added Angular Hybrid App (Angular 1 + Angular 4 ) webpack configuration.

var path = require('path');
var webpack = require('webpack');
// Webpack Plugins
var CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;
var autoprefixer = require('autoprefixer');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
/* Create multiple reference for different css bundle. 
   For example If you need two css bundle then create a 
   seperate reference for each */
var allCss = new ExtractTextPlugin('./styles/styles.css');
module.exports = {
/* Devtool is used for module debugging. multiple option string are available. The Corresponding string is to debug the original source code */
    devtool: 'inline-cheap-module-source-map',
/* Output configuration specifies the output file destination and the name. These name get the value from entry configuration */
    output: {
        path: root('./min'),
        publicPath: '',
        filename: '[name].js',
        chunkFilename: '[id].chunk.js'
    },
/* Webpack bundles the file related to the dependency graph. This entry configuration is the starting point of that dependency graph. Mostly it is the first file to kick off application. You can also give multiple entries to create a multiple bundle.
Output takes the file name from the entry objects key */
    entry: {
        'polyfills': './app/polyfills.ts',  // Output polyfill.js
        'vendor': ['./app/vendor.ts'],      // vendor.js
        'app': './app/main.ts'              // app.js
    },

/* The resolver used to find the module code that needs to be included in the bundle for every such require/import statement */
 
    resolve: {
         extensions: ['.ts', '.js', '.json', '.css', '.scss', '.html'],
         alias: {
             'npm': __dirname + '/node_modules'
            }
    },
/* Module determine how the different types of modules inside the application need to be treated */
    module: {
/* rules are array of objects used to determine how the modules need to be treated with appropriate loaders created with the help of loaders */
        rules: [
            // The files with js extension are compiled using babel-loader and added to webpack's main bundle. exclude is used to skip the un wanted files. 
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                }
            }, 
         // Files with ts extension are compiled  using awesome-typescript-loader
          {
                test: /\.ts$/,
                loaders: [{
                    loader: 'awesome-typescript-loader',
                    options: {
                        configFileName: 'tsconfig.json'
                    }
                }, 'angular2-template-loader']
            }, 
            // HTML are bundled using html-loader 
           {
                test: /\.html$/,
                loader: 'html-loader'
            }, 
           // other required application assets are bundled using normal file-loader
            {
                test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
                loader: 'file-loader?name=assets/[name].[hash].[ext]'
            }, 
            // As am using the scss here am using sass-loader for compiling and convert it into css. fallback is a kind os default loader used to bundle the css files.
            {
                test: /\.s?css$/,
                loader: allCss.extract({
                    fallback: "style-loader",
                    use: ['css-loader', 'sass-loader'],
                    allChunks: true,
                    publicPath: "./min"
                })
            }


        ]
    },
/* Plugins */ 
    plugins: [
        /* Extract text plugin reference used to seperate the css from the webpack bundle. If you have multiple reference call all the variable reference name separated by ',' */
        allCss,
        
        // Workaround for angular/angular#11580
        new webpack.ContextReplacementPlugin(
            // The (\\|\/) piece accounts for path separators in *nix and Windows
            /angular(\\|\/)core(\\|\/)@angular/,
            root('./', 'app'), // location of your src
            {} // a map of your routes
        ),
/*The CommonsChunkPlugin is an opt-in feature that creates a separate file (known as a chunk), consisting of common modules shared between multiple entry points */
        new webpack.optimize.CommonsChunkPlugin({
            name: ['app', 'vendor', 'polyfills']
        }),
/* The HtmlWebpackPlugin simplifies creation of HTML files to serve your webpack bundles */
        new HtmlWebpackPlugin({
            template: 'index.html'
        }),
        new ExtractTextPlugin('[name].css'),
    ],
/* dev server configuration */
    devServer: {
        historyApiFallback: true,
        stats: 'minimal'
    }
};
// Custom Helper functions
function root(args) {
    args = Array.prototype.slice.call(arguments, 0);
    return path.join.apply(path, [__dirname].concat(args));
}

 

Note: all the required loaders, plugin needs to be installed before use ( npm install loader-name –save-dev)

See Also: Know Basic TypeScript Features Before Starting Angular

5 Essential Browser Plugins for Frontend Developers

Along with developer tool of chrome, I have 5 essential browser plugins which make me feel more flexible with developing and debugging the web application. I always keep these plugins to make my work easy. Most you may already come across a couple of these plugins but rest will lighten and faster your development process.

Essential Browser Plugins

Essential Browser Plugins

Colorzilla

Colorzilla is a most useful and essential browser plugin for effective color sampling which allows you to pick a color from the live page or a pallet or browse colors. Along with that Colorzilla have a web page sampler that allows you to create pallet group that is used in the sampled web page. Colorzilla also has the css gradient generator which automatically generates the css code for the designed gradient.

Available for : Chrome / Firefox

Page Ruler

Most useful and flexible ruler tool to measure the pixel perfect dimension of the elements on the screen. Fast and reliable when compared to the other measuring tools available. Measuring is so simple, just click, drag and get the dimensions.

Available for :  Chrome / Firefox

Note : If you need ruler for Firefox try MeasureIt

Fontface Ninja 

Essential browser plugin to analyze and verify the font face used across the website. The lovely feature is the UI of the extension. You can also feel it by activate the extension and hover the mouse on the required text. A pop-up clearly shows the Font Family, size vertical and horizontal line spacing.

Available for : Chrome / Firefox

Css Viewer

This extension allows you to view the consolidated css property of the element. It’s so easy,  just activate the plugin by right click in the browser window and select the Css Viewer from the right popup menu.  After that hovers the mouse on the element. A new css popup panel appears and lists all the consolidated css attribute and value of the elements. Use”Esc” key to close the popup.  This extension is more helpful in debugging phase.

Available for: Chrome / Firefox

Lorem Ipsum Generator

This is a handy extension to create an appealable dummy text while developing the website. If you are developing a site in WordPress or on any CMS this extension will help you to get the dummy text in a couple of clicks. The best part is it’s an open source project.

Available for: Chrome

If you need extension for Firefox try Dummy Lipsum

Also have a look on Popular Frontend Framework you must try at least once.

Image zoom for e-commerce

Folks this time lets make some fun with implementing product image zoom for e-commerce site by using jQuery and customizing some jQuery plugins. Now lots of new frameworks and libraries available for the JavaScript. Even though jQuery still hold its better position. It is still used because of its flexibility and easy manipulation of the dom elements.

Mission

Today the mission is to implement a product zoom for a popular e-commerce site which is using jQery for dom manipulations.

Mission Accomplished

Lots of zoom plugins are available online wits lots of various features. Here am not going to give you a plugin and make you use the same for your implementation.

Am just going to explain how I implemented a product zoom by customizing already existing free plugins. sure, this combination and customization will give you a pro look for the product display page’s zoom image.

This customized product zoom has some remarkable function apart from the zooming product image. It holds the enlarged gallery and MegaEnlarge through which you can view the product more clear.

Just Download and go through the code I used simple HTML and Jquery in the way that everyone can understand. Go through the comments in zoom.js & index.html for more clarity.

Demo   |   Download

This jquery zoom implementation has four features

  1. Vertical Thumb image gallery carousel.
  2. Product Zoom
  3. Enlarged Gallery
  4. Mega Enlarge

Vertical Carousel

iZoom - ecommerce product zoomProduct Zoom

iZoom - ecommerce product zoom

Enlarged Gallery

iZoom - ecommerce product zoom

Mega Enlarge with PanZoom

 

Hotlink for demo and the working example links are dropped below just check it out!

Demo   |   Download

Plugin Credits

Product Zoom: ElevateZoom  [Free Plugin with numerous options]

Vertical Thum Gallery Carousel: rcarousel  [ Support horizontal/vertical ]

Enlarged Gallery: Fancybox

MegaEnlarge : ImagePannign.

The comments section is opened for valuable suggestion.

Happy Coding!

 

Handy Tool to compare, validate, extract & merge JSONs

I got into a case where am need to check the keys and the values for the JSON object in our project which is dropped at an even interval with updated key and values.  It is tough to identify the newly updated values and newly added keys ion the latest drop as each json holds huge number keys.  This  VEM JSON tool assists in resolving this issue.

This tool has some unique functionality like extract the non-identical Keys, Values into a separate object by comparing the source and the destination JSON. This saves time and the have high accuracy level compare to manual extraction/merging techniques while working with multilingual JSONs.

Online Tool:

https://icodefy.com/Tools/vem-json/

Git Url:

https://suriish@bitbucket.org/suriish/vem-json.git

Screenshot:

Json merging tool - screenshot

VEM JSON Tool Options

  • Compare Two JSON and Extract missing keys as a new Object.
  • Compare Two JSON and Extract keys with non-identical values and as a new Object
  • Option to merge the extracted object with Source JSON / Destination JSON
  • Add custom prefix to all the values of the Extracted JSON
  • Validate, Minify / Beautify the JSON
  • Display’s the total number of keys exist in source/ destination / extracted JSON
  • Supports multi-dimensional JSON.

Problem with Existing Tools available

  • No option to extract the Missing keys, non-Identical values as separate object
  • Merge Option are not easy and flexible
  • No option to add a prefix to the extracted values.

Solution from this Tool

  • using this tool developer can update the new key, value pair in Base resource file only, the missing keys (newly added) are extracted using the tool by comparing the old version with latest version using compare key Then those extracted keys are merged with the appropriate lingual resource file with a prefix.
  • Vem JSON tool gives High accuracy level and faster than the conventional method.
  • Developers can compare the Base (English) JSON with other lingual to identify the missed translations using compare key option and they can add a prefix to the value of extracted JSON if required. Finally, they merge the Extracted JSON with the Destination.
  • To identify and extract the values updated in the latest Drop, Developers can compare the old lingual files with the latest lingual file of using the Compare Value option in the tool.
  • The tool itself holds validation option which validates the JSON.

Additional Options

  • This tool holds JSON Error position highlighter.
  • While comparing the Keys, Extracted JSON holds the value from Source which makes the translator’s job easy.
  • While comparing the Values, Extracted JSON holds the value from the destination as it had the latest value.
  • The user can cross check the missing object counts as it displays Total key count of the JSON.
  • Pick the JSON file from your local disk for comparison.
  • Interchange Source / Destination option allow the user to interchange the source and destination JSONs easily at any time.
  • The user has the flexibility to merge the extracted JSON with Source or Destination as per the requirement.
  • Copy – allow the users to copy the entire final JSON available in the Result Section.
  • Users can manually edit and validate the JSON if required.
  • Using Minify / Beautify options user can increase the optimization / Readability respectively.

Please drop your valuable comments regarding this tool in the comments section.

If you feel that any new features need to be added in upcoming version add that also in the comment section.