Loadsh is a consistent, modular, and high-performance JavaScript utility library. For data manipulation, we often use loadsh to encapsulate some of the utility methods, but don’t want to package the entire package into the project. Here are a few ways to package Lodash on demand.

Usage:

import {isEmpty, isObject, cloneDeep} from 'lodash';
Copy the code

Existing problems:

When we only use one or two of Lodash’s methods, WebPack packs the library in, creating an unnecessary waste of resources;

fromvue-cli@3As you can see from the package analysis tool provided, lodash has70.7 KB.

There are three solutions:

1. Introduce separately

Each function in Lodash has a separate release module in NPM, and we can introduce only the modules we need.

import isEqual from 'lodash.isequal';
// 或者
import difference from 'lodash/difference';
Copy the code

When there are more modules, this writing method is more troublesome, not recommended.

2. Optimize using plug-ins

Using lodash webpack — the plugin

$ npm i --save lodash
$ npm i --save-dev lodash-webpack-plugin babel-core babel-loader babel-plugin-lodash babel-preset-env webpack
Copy the code

webpack.config.js

var LodashModuleReplacementPlugin = require('lodash-webpack-plugin');
var webpack = require('webpack');

module.exports = {
    module: {
        rules: [
            {
                use: 'babel-loader',
                test: /\.js$/,
                exclude: /node_modules/,
                options: {
                    plugins: ['lodash'],
                    presets: [['env', {modules: false, targets: {node: 4}}]]
                }
            }
        ]
    },
    plugins: [new LodashModuleReplacementPlugin(), new webpack.optimize.UglifyJsPlugin()]
};
Copy the code

With that done, lodash can be referenced once in every file where you need to use it, and any function can be called without full packaging.

3. Use lodash – es

Tree-shaking, a killer feature of Rollup, can take advantage of ES6’s static introduction specification to reduce package size and avoid unnecessary code introduction, and WebPack2 quickly introduced this feature.

When using tree-shaking, it is necessary to ensure that the referenced modules are ES6 compliant. Lodash-es is a modular version of ES6 that just needs to be introduced directly.

import {isEmpty, isObject, cloneDeep} from 'lodash-es';
Copy the code

As you can see, after using the optimization, Lodash is changed from the original70.7 KBTo reduce the20.2 KBThe effect is obvious.

Referance:

www.jb51.net/article/113…

www.npmjs.com/package/lod…