Tag Archives: WebDevelopment

Better Development Experience with Vite

Few days back I came to know about an amazing frontend tool Vite. Since then I am exploring it a bit. Here in this blog post we will go through some of the feature of Vite. We will also see how Vite can make your web development experience faster and better.

Vite – Next generation frontend tooling

There is already a discussion going on around Vite as a replacement of Webpack. In this post we will avoid this discussion. We will focus more on features of it.

What’s the need of bundling tools like Vite in your web app?

Since the ES6 modules introduced it’s a good practice to write JS code in a modular fashion. But in early days a lot of browsers were not handling loading ES6 modules natively. So we have the concept of bundling our code, using tools like webpack. The tools like Webpack and Vite converts source modules into the code that can run in the browser. These tools crawls through your code, find out dependencies and process it. Once processed it generates the bundle of all your module which can run in browser.

What are the problems with existing tools?

As we mentioned above the tools like Webpack and all, crawls through source code and process it. This works fine when you have smaller project and less no of modules. Once project grows and no of modules grows, we start experience following issues.

  • Very Slow start of dev server
  • Slow file updates
  • Slow HMR
  • Longer build time

The reason is, code transpile and concatenate takes time once your project grows. This affects the developer ‘s productivity. Every time we have to wait for the build and to start the dev server for every small changes.
So how Vite solves these issues? There are two primary things.

Pre bundling of Dependencies

When we work with web apps we use lots of vendor packages. These are external dependencies which are not going to change during the development. What Vite does is, it pre bundles these dependencies esbuild. esbuild is extremely fast JavaScript bundler.

Dependency resolving and serve

For the application source code, it resolves the dependencies and only transform and serve source code on demand. That means no time spent on bundling your source code before server starts. Here browser will take care of bundling and requesting the module as and when it’s required.

This leads to a great developer experience as we don’t have to have for serve to start. Also there is blazing fast HMR.

Here is how Vite works.

Vite work
How Vite works?

Getting Started with Vite in your React Project

Let’s see an example of how to work with Vite in your React Application. First we will start by adding necessary dependencies in your app.

"devDependencies": {
    "@vitejs/plugin-react": "^1.0.7",
    "vite": "^2.7.2"
  }

Also you have to add a config file. Following is the bare minimum configuration needed. For more options you can check out the documentation here. Vite config

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()]
})

To start the dev server with Vite, you just have to use command vite or npm run dev. Once this command is executed it will look for index.html file where you should specify your entry point.

<script type="module" src="/src/main.jsx"></script>

That’s it and it will start the dev server in fraction of seconds. If you check the network tab of your browser you can see the main.jsx is loaded as native ES module.

Vite ES native module
Vite ES native module

Fast HMR

HMR is the strategy to allow module to Hot Replace it self without affecting the page. This way we can see our changes instantly on the screen. This works fine when have smaller code but as your project grows HMR takes lots of time. This greatly affects the productivity as every time we have to wait for bundling.

When file is edited and saved it just invalidate the edited module and and its closest HMR boundary. Also if you see network tab, Vite requests the source cod with specific HTTP headers. For dependencies module requests, it uses the cache control header to cache the requests so it does not hit server. For source code module requests it uses 304 Not Modified to conditionally load it.

Because of all these features Vite is becoming popular among developers and its adoption is increasing day by day.

I will soon share my experience of replacing Webpack with Vite in larger project.

React Developer Tools for Better Development

In this blog post we will go through some of the useful React Developer Tools, that can help you in development and debugging of your React apps. Using this tool one can write better and cleaner code.

React

React Developer Tools

Some of the tools which we are going to cover here are Debugging Tools, Libraries, Test utilities etc. Using these tools you can enhance code quality and performance of your react app.

React Developer Tools I have mentioned here are based on my experience with it and use in the projects I am working on. If you know any other React Developer Tools, feel free to mention about it in comments.

React Developer Tool

This tool is available as browser extension for major browsers like Chrome, Firefox, Edge. It is also available as separate NPM package if you want to use it in mobile browser for debugging. Here is the link react-devtools

This is very popular tool, useful for both developing and debugging React apps by all the developers worldwide. Also known as React dev tool gives you a way to debug the rendered components through tab in dev tools. You can view all the props and its value for a particular component.

The feature, I like most is the, visual representation of components re render with timestamps. This is most useful for enhancing the performance of the React App.

Storybook

This is a tool for developing your React UI components separately. It helps in terms of development, testing and documentation of UI components. Imagine that you want to showcase some UI component before using it in project. Using Storybook this is possible.

As a developer, we can create develop the component and share with teams to play with it. It works outside your react project so you don’t need to make any changes in project. You can simply create components and share the storybook with your teams. Checkout official Github of Storybook

Why Did You Render

While React Developer Tool can show the visualisation of re renders, WDYR can notify you about potentially avoidable re-renders. In short it can show you the possible root cause and then you can debug more and fix it. It also works with React Native as well.

This is a nice tool for performance tweaking of your React apps. It is available as NPM package, you can install and use it in your React app. For documentation please check the official Github page of WDYR

Webpack Bundle Analyzer

This is very useful tool to for analysing the application bundle to find out which modules are heavy and which modules can be removed. It uses the webpack stats JSON file to provide us with an interactive treemap visualization of the contents of our bundle.

It is available as npm plugin so you can install and configure it to use in your React application. Checkout the official GitHub of Bundle Analyzer

JEST

Jest was created by Facebook and is a testing framework to test javascript and React apps. You can do unit testing with JEST for your React App. Unit testing is utmost important to reduce bugs in your production app.

JEST is pretty much simple to configure and use with your React App. You can add it as npm package and set up the test. Writing unit test cases are considered to be good practices for the development. You can refer to official GitHub of JEST

Frontend Development trends to Look For in 2022

As we are moving to new year 2022, it’s good to keep an eye on Frontend Development trends. You should keep up with this latest trends so you don’t miss any opportunity that could be a turning point of your career.

In this blog I am going to mention some Frontend Development trends, you should not miss out. This is based on what I have learned from industry. If you have some different opinion, feel free to share your feedback in comments.

1) Progressive Web Apps

Progressive Web Applications
Progressive Web Applications

PWA is already trending since last few years thanks to its native app like capabilities. It can be installed like native app. You can work with it offline. It is blazing fast. Major mobile browsers now support it. With PWA, you can access hardwares like camera, microphone etc.

Above all capabilities, made PWA favourite among developers and businesses operating over internet. Lots of businesses are using it and many more are vouching for it in upcoming year. Hence if you are a PWA developer you may have great chances to work with major online businesses.

2) Micro Frontend Architecture

Micro Fronend Architecture

In a simple words, it’s about breaking monolith frontend to smaller and independent applications. Together it works as one single application. This gives you more control over development and CI /CD. Many teams can work together and combining it together makes your entire frontend.

Many companies have already adopted this architecture and their productivity has been increased. This trend is going to dominate in upcoming year. If you are front end developer or architect it will be good to learn about this.

3) Rise of Voice User Interface (VUI)

Voice User Interface (VUI)
Voice User Interface (VUI)

Accessibility is a prime thing to look for in web application now a days. This gives rise to Voice User Interface. As a human, voice / language is the most natural way of communication for us. This is also another major reason behind the rise of VUI. Major companies like Amazon, Google, Apple has introduced the platforms like Alexa, Assistant and Siri. These platforms are open for developers to build applications on top of that.

Power of text to speech and speech to text technologies has increased exponentially. These gives good accessibility to your web apps. Your users can interact with apps with voice and also it is blessing for visually impaired people. There are still major challenges in this area. Like understanding regional languages. But it’s worth adding VUI in web app.

4) Rise of JAMstack

JAMstack ==> JavaScript + API + Markup

JAMstack

Core principles of JAMstack are Pre rendering and decoupling. JAMstack makes web app faster, more secure and easily scalable. You can convert your entire frontend to highly optimised prebuilt static pages which can be delivered from CDN. Let’s understand each part of JAMstack

JavaScript

As we know JavaScript is most popular when it comes to building web application. Using the modern frameworks like ReactJS, Angular, Vue and Svelte, we can develop web apps which is modularised and easy to maintain.

API

API plays vital role in JAMstack. As a developer it’s up to you that how you can make your JAMstack app dynamic by utilizing the API in proper way. From JavaScript you can make API call to multiple host which will deliver the content.

Markup

This is the most critical part of JAMstack. To be considered a JAMstack app, your app should server the HTML statically, which means not being dynamically rendered from a server. Markups is your prebuilt and pre rendered content. It is requested by JavaScript through API. Frontend developers can use frameworks like Gatsby, NextJs for this.

5) Rise of GraphQL

GraphQL

Facebook introduced GraphQL in 2018 to address the issues with REST APIs. The issue with REST APIs are you have make multiple network requests to get the entire data. This leads to performance degrade both on front end and back end. Using GraphQL we can obtain entire data with one single quest from one end point.

Few advantages of GrapQL is, it’s much faster, strongly typed and follows hierarchical structure where relationships between objects are defined in a graphical structure. Many big companies are using GraphQL. As a front end developer it’s good learn about GraphQL as more and more businesses are moving towards GraphQL

6) Web Assembly

Web Assembly

Most of the time we use JavaScript for the web development. With web assembly developer can use code written in C and C++ in web browser. WebAssembly can help client apps to run on the web that previously was not possible. Sometimes we need to build app in lower level code like C, C++ etc. For example games or streaming apps. But it can’t run on web but with Web Assembly we can write apps in C, C++, RUST, Go Lang and run on the web with near-native performance. Web assembly works along with JavaScript in browser.

7) Machine Learning / Augmented Reality / Virtual Reality

How you can leverage the power of ML, AR & VR in your web app. To know more about this check out my session on Google DevFest India 2021 Day3

Hope you liked this blog about Frontend Development trends and keep exploring it more.

Laravel Copy Tables To Other Server

Recently in one of my Laravel project, I had a situation where some of the tables are required to copy from one db server to other db server on real time basis.

Laravel Observer
Laravel

First of all I thought about using binary logging but it, but my hosting provider refused to enable binary logging. Other option is to use federated storage engine. But hosting provider refused to enable it too. In fact the tech support team asked me a question that what is Fedarated storage engine? So I gave up the hope on them. Finally I implemented with the strategy that I am going to explain in this blog.

Using Laravel Observer and Eloquent

In Laravel we can use model observers to listen to the events on models and take actions. Here are steps you have to perform.

Step 1 : Create Observer

Create a new Class in App\Http\Observers folder and name is ModelObserver

Step 2 : Assign Observer to Model

In your model file add boot function as following.

public static function boot()
{
parent::boot();
YourModelName::observe(new \App\Http\Observers\ModelObserver);
}

Step 3 : Add Methods to Your Observer

In your ModelObserver class add following methods.

public function created($model)
{

}

public function updated($model)
{

}

Now when you insert or update record with Eloquent it will invoke created and updated method and will send model instance as param.

Replication to Other Server

Now next step is to implement replication strategy. For this we are going to create separate model and use remote server connection with that model.

Step 1 : Save Remote Host Connection

For this first of all create saparate MySql connection in your config/database.php file

‘replica’ => [
‘driver’ => ‘mysql’,
‘host’ => env(‘REPLICA_DB_HOST’, ‘remotehost’),
‘port’ => env(‘REPLICA_DB_PORT’, ‘3306’),
‘database’ => env(‘REPLICA_DB_NAME’, ‘your_db’),
‘username’ => env(‘REPLICA_DB_USERNAME’, ‘your_username’),
‘password’ => env(‘REPLICA_DB_PASSWORD’, ‘your_password’),
‘charset’ => ‘utf8’,
‘collation’ => ‘utf8_unicode_ci’,
‘prefix’ => ”,
‘strict’ => false,
‘engine’ => null,
]

Step 2 : Create Model to Connect to Remote Host

Now create a separate model and assign remote server connection to it.

<?php

namespace App\Http\Models;

use Illuminate\Database\Eloquent\Model;

class RemoteModel extends Model
{
protected $connection= ‘replica’;
protected $table = ‘remote_table’;
}

Step 3 : Replicate Model

Now inside your observer’s created method add following code.

if($model instanceOf \App\Http\Models\Model){
$modelArray = $model->toArray();
$newModel = new \App\Http\Models\RemoteModel;
foreach( $modelArray as $key => $value ){
if(gettype($modelArray[$key]) != ‘array’){
$newModel[$key] = $modelArray[$key];
}
}
$newModel->save();
}

As you can see in above code that we are checking first if model created is type of our Model Class and then creating object of RemoteModel and assigning values of Model to RemoteModel object and then finally call save method, this will create row in remote table on remote server.