This article was translated from GoogleChromeLabs

Using a third-party library in a Webpack project? Use these methods to shrink the bundle!

async

Async is a set of utilities for handling asynchronous functions.

In general, you should use Async-es. It comes with the ES module and is more suitable for WebPack packaging.

Still, even if you prefer async, see the Async-ES section for a list of optimizations.

async-es

Async-es is a set of utilities for handling asynchronous functions. It is the same as Async, but it is better for Webpack packaging.

usebabel-plugin-lodashDelete unused methods

If you use async-es as a single import, you package the entire library into your application — even if you only use a few of its methods:

// You only use 'async.map', but the whole library is packaged
import async from 'async-es';

async.map(['file1'.'file2'.'file3'], fs.stat, function(err, results) {
  console.log(results);
});
Copy the code

Use babel-plugin-lodash to select only the async-es methods you need:

// Before applying Babel
import async from 'async-es';

async.map(['file1'.'file2'.'file3'], fs.stat, function(err, results) {
  console.log(results);
});
Copy the code

left

// After applying Babel
import _map from 'async-es/map';

_map(['file1'.'file2'.'file3'], fs.stat, function(err, results) {
  console.log(results);
});
Copy the code

Enable this plug-in as follows:

// .babelrc
{
  "plugins": [["lodash", { "id": ["async-es"] }]],
}
Copy the code

babel-polyfill

Babel-polyfill is a Babel package that loads core-JS and a custom regenerator runtime.

See the core-js section for a list of optimizations.

core-js

Core-js is a set of polyfills for ES5 and ES2015+.

usebabel-preset-envRemove unnecessary polyfills

If compiling code using Babel and babel-preset-env, add the useBuiltIns: true option. This option configures Babel to contain only the polyfill required by the target browser. For example, if you position your application to support Internet Explorer 11:

// .babelrc
{
  "presets": [
    [
      "env",
      {
        "targets": {
          "browsers": ["last 2 versions", "ie >= 11"]
        }
      }
    ]
  ]
}
Copy the code

Enable useBuiltIns: True will remove polyfills for all functions already supported by Internet Explorer 11 (e.g. Object.create, object. keys, etc.).

Send non-conversion code to modern browsers

All browsers that support

date-fns

Date-fns is a date utility library.

To enable thebabel-plugin-date-fns

Babel-plugin-date-fns replaces the full import of date-fns with an import of the date-specific function function:

import { format } from 'date-fns';
format(new Date(2014.1.11), 'MM/DD/YYYY');
Copy the code

left

import _format from 'date-fns/format';
_format(new Date(2014.1.11), 'MM/DD/YYYY');
Copy the code

lodash

Lodash is a library of utilities.

To enable thebabel-plugin-lodash

Babel-plugin-lodash replaces the full LoDash import by importing specific LoDash functionality:

import _ from 'lodash';
_.map([1.2.3], i => i + 1);
Copy the code

left

import _map from 'lodash/map';
_map([1.2.3], i => i + 1);
Copy the code

Note: This plugin does not apply to method chains – such code will not be optimized.

_ ([1.2.3]).map(i= > i + 1).value();
Copy the code

forlodash-esAn alias forlodash

Some dependencies may use Lodash-es instead of LoDash. If so, Lodash will pack twice.

To avoid this, alias the Lodash-es package to Lodash:

// webpack.config.js
module.exports = {
  resolve: {
    alias: {
      'lodash-es': 'lodash',}}};Copy the code

To enable thelodash-webpack-plugin

Lodash – Webpack-Plugin strips loDash functionality that you don’t need. For example, if you use _.get() but don’t need deep path support, this plug-in can remove it. Add it to your WebPack configuration to make packaging smaller.

Use this plug-in with caution. The default Settings remove many features, some of which may be used by your application.

lodash-es

Lodash-es is the ES module of LoDash.

For a list of optimizations, see the Lodash section ⤴.

moment

Moment.js is a library that handles dates.

usemoment-locales-webpack-pluginDelete unused languages

By default, moment.js comes with 160 + KB of compressed localized files. If your application provides only a few languages, you don’t need all of these files. Remove unused languages using moment-locales-webpack-plugin.

Use this plug-in with caution. Delete all locale Settings by default; If you use some of these, this may break your application.

react

React is a library for building user interfaces.

Delete in productionpropTypesThe statement

React does not perform propTypes checking in production, but propTypes declarations still occupy a portion of the bundle. Remove them from the build process using babel-plugin-transform-react-remove-prop-types.

Migrate to another library similar to React

React alternatives have a similar API, with a smaller size or higher performance, but lack some functionality (for example, Fragments, Portals, or composited events).

Migrate to alternatives carefully. Some alternatives have no compositing events or lack some React 16 features (Preact Issue, Inferno issue, Nerv Issue). However, many projects can still be migrated without any code base changes. See migration guidelines: Preact, Inferno, Nerv.

reactstrap

Reactstrap is the React library based on Bootstrap 4.

usebabel-plugin-transform-importsDelete unused modules

When importing a module from Reactstrap:

import { Alert } from 'reactstrap';
Copy the code

Other Reactstrap modules are also packaged into the application and made larger.

Use babel-plugin-transform-imports to remove unused modules:

// .babelrc
{
  "plugins": [
    ["transform-imports", {
      "reactstrap": {
        "transform": "reactstrap/lib/${member}",
        "preventFullImport": true
      }
    }]
  ]
}
Copy the code

To see how it works, see the babel-plugin-transform-imports section.

react-bootstrap

React – Bootstrap is the Bootstrap 3 library based on React.

usebabel-plugin-transform-importsDelete unused modules

When importing modules from react-Bootstrap:

import { Alert } from 'react-bootstrap';
Copy the code

Other React-Bootstrap modules will also be packaged into the application and made larger.

Use babel-plugin-transform-imports to remove unused modules:

// .babelrc
{
  "plugins": [
    ["transform-imports", {
      "react-bootstrap": {
        "transform": "react-bootstrap/es/${member}",
        "preventFullImport": true
      }
    }]
  ]
}
Copy the code

To see how it works, see the babel-plugin-transform-imports section

react-router

React Router is the popular Router solution for React.

usebabel-plugin-transform-importsDelete unused modules

When importing a module from the React Router:

import { withRouter } from 'react-router';
Copy the code

Other React Router modules will also be packaged into the application and made larger.

Use babel-plugin-transform-imports to remove unused modules:

// .babelrc
{
  "plugins": [
    ["transform-imports", {
      "react-router": {
        "transform": "react-router/${member}",
        "preventFullImport": true
      }
    }]
  ]
}
Copy the code

(This was tested using React Router V4.)

To see how it works, see the babel-plugin-transform-imports section.

styled-components

Styled – Components is a CSS-in-JS library.

usebabel-plugin-styled-componentsThe compression code

The babel-plugin-styled- Components plug-in compresses CSS code written in Styled – Components. Please refer to the relevant documentation.

whatwg-fetch

Whatwg-fetch is a complete window.fetch() polyfill.

Replace withunfetch

Unfetch is a 500-byte polyfill of window.fetch(). Unlike WHATWG-Fetch, it does not support the full Window.fetch () API, focusing instead on the parts polyfill uses most often.

Migrate cautiously to Unfetch. Although it supports the most popular parts of the API, if it relies on something less common, your application may not function properly.

A solution for multiple libraries

Of course, there are other library optimization tips as well. You can use them with common sense for smaller or higher performance bundles.

babel-plugin-transform-imports

This handy Babel plug-in converts your imports to importing only specific components, which ensures that the entire library is not included.

// Before
import { Grid, Row, Col } from 'react-bootstrap';
// After
import Grid from 'react-bootstrap/lib/Grid';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
Copy the code