简体   繁体   中英

Lodash Dead Code Removal in ES6

I've been using lodash in my applications and libraries and I've been packaging my applications and libraries with webpack (and UglifyJS ).

The problem with this is that when minifying, if you imported lodash in its entirety, UglifyJS doesn't know to remove the functions from lodash that are unused. Clever people have come up with importing just the functions you're going to use from lodash, like so:

var forEach = require('lodash/array/forEach');

This works great and results in a much smaller compiled version of my code. However, it can be very tedious in files that use many parts of lodash.

Can the same effect be achieved using ES6-style imports and Babel 's DCE transformer ? For example:

import { forEach } from 'lodash';

I'm suspicious since it's importing from the the root of the lodash library and not from the individual function's file like the former example.

Given you are likely using Babel already, I think babel-plugin-lodash can do the trick. It is able to perform transformation from

import lodash from 'lodash';

lodash.map([1, 2, 3], function(x) {
    // ... 
});

to

import _map from 'lodash/collection/map';

_map([1, 2, 3], function(x) {
    // ... 
});

IMPORTANT! As mentioned by @reflog at comments, this approach doesn't work with lodash chaining!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM