An Intro into webpack

Among various module bundlers, webpack turns out to be the most popular and powerful one due to its many features like improved performance and load time, to name a few! If you’re not familiar with it, I hope this blog will get you started with this powerful tool.

So, What exactly is a webpack?

A webpack is a powerful module bundler for JavaScript applications that packages all the modules in your application into one or more bundles (often, just one) and serves it to the browser. However, Webpack is more than just a module bundler. With the help of loaders and plugins, it can optimize, transform and minify all types of files before serving them as one bundle to the browser. 

It takes in various assets, such as JavaScript, HTML, CSS, Fonts, and Images and then transforms these assets into a format that’s convenient to consume through a browser. And I think this is fair enough to go ahead with webpack.

Understanding core concepts:

There are 4 key concepts in webpack that will cover an overall view of webpack and it’s configuration. Let’s get started.

  1. Entry Point:

An entry point indicates which module, the webpack should use to begin building out its internal dependency graph. webpack will figure out the entry point’s dependencies. By default, its value is ./src/index.js, but you can specify a different (or multiple entry points) by configuring the entry property in the webpack configuration.

Include the following in the webpack.config.js file

module.exports = {
  entry: './path/to/my/entry/file.js'
};
  1. Output:

Output defines where to emit the bundled files and assets. The following snippet tells out how the output can be configured in webpack.config file.

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'
  }
};
  1. Loaders: 

webpack understands only JS and JSON files, so in order to allow webpack to identify other file types, Loaders came into the picture. It defines the webpack to transform other types. It has two main properties, test, a regex pattern for testing the type of files and use for using the specific loaders for that type.

const path = require('path');
module.exports = {
   output: {
     filename: 'my-first-webpack.bundle.js'
},
module: {
    rules: [{ 
            test: /\.txt$/
            use: 'raw-loader' 
    }]
};
  1. Plugins: 

While loaders are used to transform various modules, plugins can be used to perform a wider range of tasks like bundle optimization, asset management and injection of environment variables. Plugins are customizable through options. We need to require() a plugin and need to create an instance of that using the new operator.

const HtmlWebpackPlugin = require('html-webpack-plugin'); 
const webpack = require('webpack'); 
module.exports = {
  module: {
    rules: [
      { test: /\.txt$/, use: 'raw-loader' }
  },
  plugins: [
    new HtmlWebpackPlugin({template: './src/index.html'})
};

How webpack works?

Webpack seems to be a mystery in the JavaScript world. So let’s go ahead and get some working examples to understand how it works. But before that, let’s make some basic setup to proceed with.

npm i -D webpack webpack-cli

Also, add build scripts to package.json

  1. Bundling JS

Create an src folder because webpack always looks for a source folder and index.js file before bundling JS. Now, if you run the npm run build, a dist folder will be created along with a main.js file that bundles your source file.

  1. Bundling HTML

Create an index.html file under the source folder and add the created index.js file into the script tag. Now, if you run build, you’ll get a syntax error. By now, you should have probably known the reason behind it. Yes! webpack doesn’t recognize any other type except JS. So let’s configure webpack for fixing this.

Create a webpack.config.js file and pre-install a loader to allow webpack to transform HTML files.

npm i -D html-webpack-plugin html-loader

Then configure the installed loader into the webpack config file and after that, now webpack will be able to bundle the HTML files as well.

  1. Bundling Image

Webpack neither bundles images so that we need to install a loader to allow webpack to do that.

npm i -D file-loader

Then configure the loader in webpack and create an image folder and put an image inside that. Also, include the image in img tag inside the index.html file and run npm run build. Now webpack bundles your images as well.

  1. Bundling Scss

I hope now there is no need to say that again. So let’s get straight towards installing loaders for bundling styles and see it bundled after configuring that in webpack.

npm i -D node-sass style-loader css-loader sass-loader mini-css-extract-plugin

webpack.config.js

Let’s have a look into the final code structure of webpack.config.js after all the above configurations.

const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
   module: {
       rules: [{
               test: /\.html$/,
               use: [{
                   loader: "html-loader",
               }]
           },
               test: /\.(png|svg|jpg|gif)$/,
               use: [
                   'file-loader'               
           },
               test: /\.scss$/,
               use: [
                   'style-loader', 'css-loader', 'sass-loader'
           },
   },
   plugins: [
       new HtmlWebpackPlugin({
           template: "./src/index.html",
           filename: "./index.html"
       }), 
       new MiniCssExtractPlugin({
           filename: "[name].css",
           chunkFilename: "[id].css"
       })
}

References

  1. https://webpack.js.org/
  2. https://www.youtube.com/watch?v=TzdEpgONurw

Speech Recognition with Javascript

Have you ever wondered how marvelous the technology is growing and has brought tremendous improvements in our lives? The rise of Artificial Intelligence and Machine Learning indicates that Robots and machines are our new human model in the future. So, what else we’ll do in this tech world without getting updated with technology. Let’s get started with the most popular AI technology i.e., Speech Recognition.

Voice is the future as well as the present. So anything that you brand with voice is going to be a massive hit. Because humans are fascinated by a machine that can understand us! Let me bring some statistics of voice recognition used almost everywhere.

According to Adobe Analytics, 71% of owners of smart speakers like Amazon Echo and Google Home use voice assistants at least daily, and 44% using them multiple times a day.

Over 76% of smart speaker owners increased their usage of voice assistants in the last year.

So, 50% of searches will be voice by 2020.

A little while ago, I got an opportunity to implement the Speech recognition to one of our Applications. I was really overwhelmed to work on the most talked technology and bumped into the google search about the possible ways to implement the same. I’ve come across several npm modules, most of them are really cool to proceed with. Amongst various npm modules and technologies, I found this JavaScript web speech API is so simple and accurate to go with the speech recognition process.

It is a very powerful browser interface that allows JavaScript to have access to a browser’s audio stream and convert that to text. The Web Speech API is actually separated into two independent interfaces. We have SpeechRecognition for understanding human voice and turning it into text (Speech -> Text) and SpeechSynthesis for reading strings out loud in a computer-generated voice (Text -> Speech). 

The first thing that we need to do is to check the Browser compatibility table carefully before using this in your work or else you would be jammed with errors. 

Note: I’ll list down the things that are implemented in Angular application and I don’t think there will be much difference in implementing this in other frameworks of JS.

Voice to Text

Step:1

Let’s create an interface for the webkitSpeechRecognition like this,

export interface IWindow extends Window {
    webkitSpeechRecognition: any;
}

Step:2 

Now initialize the webkitSpeechRecognition to a variable like this,

const { webkitSpeechRecognition }: IWindow = window as IWindow;

   this.recognition = new webkitSpeechRecognition();

Step:3

There are some properties to make the speech API to function as per the configuration of that.  

The continuous property controls whether continuous results are returned for each recognition or only a single result. It defaults to single results (false.)

The interimResults property controls over the display of results. If set true, the results will be streaming live. The default value for interimResults is false which displays the text at the end.

We could also set the language, grammar and various others through its properties.

this.recognition.continuous = true;

this.recognition.interimResults = true;

this.recognition.lang = 'en-US';

All set. We’re done with the initial setup without any installations. We made it too simple and Now it’s good to go! 

Event Handlers

There are many event handlers in this API where you can track every event and perform whatever you want to. The following are the most used events.

  • onstart: This event is triggered when speech recognition is started. This is where we could show some notifications to the user that they can start speaking.
  • onresult: This is the most important event where we could track this and get the text string that is processed from a user’s speech recognition.
this.recognition.onresult = (event) => {

     let interimTranscript = '';

     let finalTranscript = '';

     for (let i = event.resultIndex; i < event.results.length; ++i) {

       if (event.results[i].isFinal) {

         finalTranscript += event.results[i][0].transcript;

       } else {

         interimTranscript += event.results[i][0].transcript;

        }

     }

     this.message += finalTranscript; // Processed message

   };
  • onerror: This is as important as handling onresult because the user might not know when their process stopped due to some reasons. So notify the user regarding this error and try to restart or stop the recognition or do whatever!
  • onend: A simple event that gets triggered when our recognition is stopped. 

Methods:

There are three important methods in web speech API which is highly useful to invoke the actual speech recognition functions. Just keep reminded that only after calling methods, the respective events will get triggered. So let’s know when to call a method.

  • start(): It starts the speech recognition service listening to incoming audio with intent to recognize grammar associated with the API.
  • stop(): It stops the speech recognition service from listening to the incoming audio and attempts to return a result using the audio captured so far.
  • abort(): It stops the speech recognition service from listening to the incoming audio and doesn’t attempt to return a  result.

Text to Speech

Actually, text to speech is really very easy. It is accessible through the speechSynthesis object and there are a couple of methods for playing, pausing and other audio related stuff like changing the pitch, rate, and even the voice of the reader. But we can do it simply with the speak() method. Here is the entire code needed to read out a string.

textToSpeech(message) {

   const speech = new SpeechSynthesisUtterance();

   // Set the text and voice attributes.

   speech.text = message;

   speech.volume = 1;

   speech.rate = 1;

   speech.pitch = 1;

   window.speechSynthesis.speak(speech);

When this function is called, a robot voice will read out the given string, doing its best human impression.

Conclusion:

It was cool. Isn’t it? Since conversational user interfaces and voice assistants are becoming more popular, we can build that with this simple and cool web speech API. I hope this blog has given some quick and simpler ways to implement speech recognition. Adding voice-based user interaction to your application would be a great form of user experience. So what are you waiting for? Just go ahead and do some wonder with voices.

References:

  1. https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition
  2. https://www.google.com/intl/en/chrome/demos/speech.html
  3. https://shapeshed.com/html5-speech-recognition-api/

 

Lint Driven Development

It is no wonder that “Lint Driven Development – LDD” is one of the most essential development approach that every developer should follow up! It is an integral part of every developer’s toolbox! If you could agree my statement, then you’re already on the track of super cool development. If not, then I can get you a step further towards that through this blog.

What is linting?

You write code. Probably a lot of code. And you make mistakes. Probably a lot of mistakes. Sometimes your mistake is a real bug that can be fixed. Sometimes it’s just an unclear coding style which may seem trivial at first but they become patently important as the codebase grows and as more people stick their hands in it. You can’t always focus on fixing this inevitable mistakes that you do! Isn’t it? Because, there is probably no practical way to make it impossible to write sloppy and unclear code, but it is fascinating to consider how tooling has evolved to make it harder. One fine tooling is “Linters” which understands you and your code.

Linter is part of the style guide. It’s a small piece of software that automatically checks if your code has any stylistic or potential errors and meets the predefined code convention rules. You don’t have to manually go through the code base to check style and any errors. Linting helps us in two ways. First, it looks for code that will potentially break. Second, it provides a style guide for the development team to follow.

Why Linting is Important?

Some great movies involves compelling stories, and colorful screenplays that are easy to watch and understand. From that aspect, the job of a developer is similar to that of the movie director, since the code has to be easy to read and comprehensive. I know it’s pretty hard to focus on code quality when you’re under pressure to meet the next deadline, but if you’re thinking long term, you definitely need to write code that’s readable and maintainable.

In addition to its readability and maintainability there lies an important third reason which is lower technical debt which allows speeding up long term software development since it can be reused without involving any future developer’s time to work on fixing the old bugs and styling the code.

How Linters prevent our problems?

Linting tools throws warnings about certain types of code that can lead to common problems. Some are quite major. As a Javascript Engineer, I’ll list down some major problems in JS code and how linters could prevent those problems!

Problem #1
Most of us have got this one common question in our mind that our code works in development but why not in production? We all knew that most modern web stacks support minification, but neither the minifiers nor the browser tell us when are we missing semicolons. But a missing semicolon can break minified javascript and so it stops in production. So Linters notify you about the missing semicolons, braces, etc..

Problem #2:

Have you ever created a variable called “id” or “name” or “value”? Yeah, so has every other developer in history, and people who work on the same codebase as you is not an exception. And if someone forgets to declare all their variables with var, as they can overwrite each other unexpectedly. The scope of the variables is gone as well as your code.

You don’t always need to rely on your reviewers to find mistakes in your code and in some cases it takes too much of your reviewer’s time to find some sloppy mistakes or even they might miss it completely. Linting your JS can prevent potential XSS security holes, readability problems, and many more!

Linting Tools

Linters comes with a lot of tools that are capable of finding stylistic errors and sloppy mistakes in every technology that we use. Among many JS linters, ESLint seems to be the best available linter as it is completely plug-able, every single rule is a plugin and we can add more rules at run-time. It gives concise output, and also includes the rule name by default so it’s always easy to know which rules are causing the errors. We also have Linters for most languages like TS, CSS, HTML, Python, etc..

There are different means by which one can use linting tools to improve the code quality. To mention a few,

Linting manually, in the browser

Copy and Paste your code into JSHint or CSSLint or HTMLHint or any other static code analysis tool to check for some interesting lint errors. This might be the quickest way to get started with linting.

Linting from your code editor

Many code editors have support for configurable linting, such as VSCode. Here is the guide to configure Linters in VSCode. It has many extensions for all of the linters above. Grab one and have it check your code automatically which is really great since you’re already in your editor, where you can clean your code up simultaneously while you write it.

Linting from the command line

If you’re using a command line tool like Npm, you’re ahead of the curve. Just install a linter of your choice and follow some commands to get notified of your errors in code.

Linting as part of the build process

This is the best way to ensure that these types of problems never see the light of day. I recommend adding a flag to the ng serve and the ng build commands that automatically runs ng lint before each build and causes a build failure on any linter rule violation.

Even if you set up a linter, it might warn you against invalid code but it cannot stop you from pushing this code to the repo. This is where Git pre-commit hook comes into the picture. It’ll restrict the developer from committing the code if it doesn’t pass the rules available in .git/hooks. For information about Git Hooks, please visit here.

It is NoteWorthy!

I recommend turning off most of your linter’s settings when you start using it, so that you have a minimal set of errors to start with. Consider the ones it throws out, learn what they mean and then fix them. Later, re-enable another setting and repeat until you understand all the rules. I understand, it takes some time to understand everything and to get them fixed up. Let me copy out some words from Bruce Lee.

“I fear not the man who has practiced 10,000 kicks once,

         but I fear the man who has practiced one kick 10,000 times.”

– Bruce Lee

Software development is pretty much always slower than anyone wants it to be. It takes time. Sometimes you just have to be patient enough to turn out the code you need to write. No matter how long you’ve been in this field, you should keep practicing the craft of coding.

Conclusion

Linting is a vital part of our workflow, and will definitely help us improve our skills. If you were not using linting, I hope this blog convinced you a bit to configure lint to your code. I think Linting is one of the traits that makes a good developer! What do you think makes a great developer? Love to hear from you!

Materialise your Angular App

As much as I love Angular, I also recognize that there are a few things that could make your Angular App look even more stunning without much effort! So, let’s go ahead and change your life in about 5 minutes by getting productive with Material Design using Angular Material in your Angular CLI app.

So, What Exactly is Angular Material?

Angular Material Design is a design language for web and mobile apps which was developed by Google in 2014. Material Design makes it easy for developers to customize their UI while still keeping a good-looking app interface that users are comfortable with and also you’ll get a well-organized format along with the flexibility to express your brand and style. For an example of Material Design, check out Airbnb, Gmail, and Houzz. These apps make the best use of Material Design to fit its many features into the limited mobile device. Going through the official Material design documentation is quite an experience. I recommend taking a look at the docs, but I will summarize it here.

Setup the Environment for Angular

To work with Angular, you will need Node.js and Angular CLI (Command Line Interface) installed in your development environment. Proceeding further, you can use the following command to set up a new Angular project.

ng new angular-material-app

Step 1: Install Angular Material and Cdk

Head over to your terminal, navigate inside your created Angular front-end application and then run the following commands to install Angular Material 6 and Angular 6 CDK.

npm install --save @angular/material @angular/cdk

Step 2: Install Angular Animations

In order to add enable support for animations in your Angular 6 front-end application, head back to your terminal and run the following command to install the Angular animations module and import the BrowserAnimationsModule and add it to the list of imports.

npm install --save @angular/animations

Step 3: Angular Material Theme

Angular Material comes prepackaged with several pre-built theme CSS files. To configure the basic theme, open the src/styles.css file and import any one of the available themes in Material Themes.

@import '~@angular/material/prebuilt-themes/indigo-pink.css';

Step 4: Angular Material Gesture

Some components like Slide Toggle, Slider, and Tooltip rely on a library called HammerJS to capture touch gestures. So, you will need to install HammerJS and import it into our application.

npm install --save hammerjs

Step 5: Angular Material Icons (Optional)

If you want to use the mat-icon component with the official Material Design Icons, load the icon font in your index.html. For more information on using Material Icons, check out the Material icons guide.

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

And yeah, Now you are good to go!

Note:  You can create an app-material module file for importing the angular material components and export them wherever necessary! Let’s write clean code and be a Better programmer!

What Will You Build with Angular Material?

After setting up the project structure and some dependencies, you will be able to start developing apps. You could try out some examples with the built-in components that are provided in Material docs. In this blog, to know about Angular material implementation, we will be implementing it with some small examples that play a major role in any webpage! The idea of this blog is to show how cool and easy it is to use Angular Material.

Example 1: Layout

The most widely used layout is cards. The most basic card needs only an <mat-card> element with some content. However, Angular Material provides a number of preset sections that you can use inside of an <mat-card>. For now, just copy the following code into your HTML file and you could witness a card display!

<mat-card> Simple Card</mat-card>

Example 2: Navigation

Next comes the navigation part of a webpage. <mat-menu> is a floating panel containing the list of options. By itself, the <mat-menu> element does not render anything. The menu is attached to and opened via application of the matMenuTriggerFor directive as follows.

<button mat-button [matMenuTriggerFor]="menu">Menu</button>
 <mat-menu #menu="matMenu">
   <button mat-menu-item>Item 1</button>
   <button mat-menu-item>Item 2</button>
 </mat-menu>

Example 3: Progress Bar

    “Boredom, according to psychologists, is merely lack of stimulation,the unfulfilled desire for satisfying activity. So what if we use the interface to give them that stimulation?”

~ Alice Kotlyarenko

Yeah! The UI progress bar will make you enjoy the wait! Angular Material made it easy to display a progress bar with customizable modes.

<mat-progress-bar mode="indeterminate"></mat-progress-bar>

Conclusion

I hope this blog has helped you understand how to use the power of Material Design in your app for a top-notch UI. For more information about Material Design in Angular 6, check out the official docs which contain ready-to-use templates. It’s a great place to learn about Angular. Thus Angular Material components create a beautiful application without investing too much time thinking about styles. Awesome, right?

Reference: