• Programming
  • Tutorial
  • System Administration
  • Gadgets
  • Phones
  • Web development
Thursday, May 19, 2022
  • Login
No Result
View All Result
SkilledRoom
No Result
View All Result
SkilledRoom
No Result
View All Result
Home Programming

5 Ways to Reduce JavaScript Package Size

December 3, 2021
in Programming
Share on FacebookShare on Twitter

JavaScript is used heavily in modern web development. And the packages of many applications are getting quite large. It seems to be okay, but when a certain limit is reached, it starts to negatively affect the performance of the application.

In this article, I’ll walk you through five ways to reduce the size of JavaScript packages and thereby avoid performance issues.

1. Code splitting using Webpack

Splitting code allows you to distribute all your code into packages and download them only when needed.

There are many ways to implement code splitting with Webpack . One of the most used is dynamic imports. With this approach, you can easily split your code into parts depending on the routes used in the frontend of the application.

Let’s say you are creating a new social network. Social media users are most likely to interact with their news feed and profile page. Thus, at first it will be enough to download these two pages, and download the rest on demand.

If you are using Angular or React, it will be even easier to split the code. These frameworks support lazy loading by default.

import React, { lazy } from 'react'

const App = (props) => (
  ...
        <Route exact path="/" component={lazy(() => import('routes/home'))} />
        <Route path="/profile" component={lazy(() => import('routes/profile'))} />
        <Route path="/settings" component={lazy(() => import('routes/settings'))} />
  ...
)

This example demonstrates lazy loading of components in React. Once you define them, Webpack takes care of the rest.

Creating independent components for layout or assembly or runtime (using dynamic imports) is now an easy task.

2. Using Webpack plugins for Tree shaking

Webpack uses a dependency graph for generating packages, which consists of all the modules in the application. As the program grows, many dead or unused lines of code may appear in this tree. As a result, application performance drops.

Tree shaking is a technique used to remove dead code. Webpack provides several plugins to implement Tree shaking.

babel-plugin-lodash

If you are using lodash in your application , you may need to use the babel-plugin-lodash plugin.

This plugin allows you to choose from lodash those things that need to be imported (since not everything that is there, we need).

All you need to do is install babel-plugin-lodash using npm or yarn and update the Webpack config:

// Installation

npm install --save-dev babel-plugin-lodash

// Usage

'module': {
  'loaders': [{
    'loader': 'babel-loader',
    'test': /\.js$/,
    'exclude': /node_modules/,
    'query': {
      'plugins': ['lodash'],
      'presets': [['@babel/env', { 'targets': { 'node': 6 } }]]
    }
  }]
}

babel-plugin-import

babel-plugin-import allows Webpack to select only the lines of code it needs when traversing the dependency graph. Unlike babel-plugin-lodash, this plugin is not limited to lodash: you can use it with packages like antd as well.

// Installation

npm install --save-dev babel-plugin-import

// Usage

webpackConfig.module.rules = [
  {
    test: /\.(js|jsx)$/,
    include: [path.resolve(__dirname, 'src', 'client')],
    use: [{
      loader: 'babel-loader',
      options: {
        plugins: [
          [
            'import',
            { libraryName: 'antd', style: true },
            'antd',
          ]
        ],
      },
    }],
  },
]

Apart from these two plugins, there are many others, you can choose according to the requirements of your project.

3. Using alternative libraries and removing duplicates

Keeping track of package sizes in applications is a good developer habit. It helps you easily figure out where performance issues come from and find packages that need optimization.

Webpack bundle analyzer visualizes the size of bundles in the application.

You can use the Webpack bundle analyzer by importing it into the Webpack config as a plugin, or using CLI commands.

// Installation

npm install --save-dev webpack-bundle-analyzer
// or
yarn add -D webpack-bundle-analyzer

// web pack config

import WebpackBundleAnalyzer from 'webpack-bundle-analyzer'
webpackConfig.plugins = [
  new WebpackBundleAnalyzer.BundleAnalyzerPlugin(),
]

// CLI commands - This weill generate a json file with stats

webpack --profile --json > stats.json

This analysis will give you a clear understanding of all the libraries used in your project and how they affect JavaScript package size. In addition, you can find duplicate libraries in the package and, based on the analysis, decide which ones should be removed or replaced.

4. Packet compression

If your application’s JavaScript packages grow in size and begin to take a toll on performance, you can compress them. The most commonly used compression techniques are Gzip and Brotli. To simplify the process, you can use Webpack plugins.

Note. Brotli compresses JavaScript files 14% better than Gzip, according to research by CertSimple .

You can use the compression-webpack-plugin to compress files using Gzip . Or if you prefer Brotli, use the brotli-webpack-plugin . Both plugins are available on NPM, you just need to download them and edit the Webpack config:

// For GZIP

// Instalation

npm install compression-webpack-plugin --save-dev

// Usage
const CompressionPlugin = require("compression-webpack-plugin");
module.exports = {
  plugins: [new CompressionPlugin()],
};


// For Brotli

// Instalation
npm install --save-dev brotli-webpack-plugin

// Usage

var BrotliPlugin = require('brotli-webpack-plugin');
module.exports = {
  plugins: [
    new BrotliPlugin({
      asset: '[path].br[query]',
      test: /\.(js|css|html|svg)$/,
      threshold: 10240,
      minRatio: 0.8
    })
  ]
}

5. Using Production Mode in Webpack

Running a project in production mode reduces the package size compared to development mode. Webpack provides a special flag to enable this feature -p. This flag removes all spaces and newlines in your code.

webpack -p --mode=production

Conclusion

The development of modern web applications is not only about creating the basic functionality. We need to focus on productivity, productivity and efficiency to get the most out of our efforts.

JavaScript package size is a significant factor in application performance. Unfortunately, the more JavaScript we use, the more difficult it becomes to control the packet size.

I hope you find the five ways to reduce packet size outlined in this article helpful.

Tags: JavaScriptWeb development
Previous Post

40 JavaScript Techniques You Should Know

Next Post

Galaxy S21 Ultra, good for movies: how spectacular is the first feature film with a Samsung phone

Related Posts

40 JavaScript Techniques You Should Know

40 JavaScript Techniques You Should Know

by skilled
December 3, 2021
0

JavaScript is a programming language used to build web pages and mobile applications. If you've been learning JS for a while...

Pip: how to install packages in Python

Pip: how to install packages in Python

by skilled
December 3, 2021
0

Pip is a package manager for Python and can be accessed through the command line. Pip does not need to be installed...

Python vs C ++ speed comparison

Python vs C ++ speed comparison

by skilled
December 3, 2021
0

An example for data scientists who think they don't need to learn C ++ Prim. row.This is a translation of Nazer...

Next Post
Galaxy S21 Ultra, good for movies: how spectacular is the first feature film with a Samsung phone

Galaxy S21 Ultra, good for movies: how spectacular is the first feature film with a Samsung phone

Samsung is finally solving the most annoying problem on its top phones

Samsung is finally solving the most annoying problem on its top phones

The new Galaxy S22: specifications, camera and battery capacity: why it competes with the iPhone 12 mini

The new Galaxy S22: specifications, camera and battery capacity: why it competes with the iPhone 12 mini

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Home
  • About Us
  • Advertise
  • Privacy & Policy
  • Contact Us

© 2017 JNews - Premium WordPress news & magazine theme by Jegtheme.

No Result
View All Result
  • Programming
  • Tutorial
  • System Administration
  • Gadgets
  • Phones
  • Web development

© 2017 JNews - Premium WordPress news & magazine theme by Jegtheme.

Welcome Back!

Login to your account below

Forgotten Password?

Create New Account!

Fill the forms below to register

All fields are required. Log In

Retrieve your password

Please enter your username or email address to reset your password.

Log In