Uninstall Lodash Dead Code in ES6

I used lodash in my applications and libraries, and I was packing my applications and libraries using webpack (and UglifyJS ).

The problem is that when minimizing, if you imported lodash completely, UglifyJS does not know to remove functions from lodash that are not used. Smart people came up with importing only those functions that you are going to use from lodash, for example:

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

This works fine and leads to a much smaller compiled version of my code. However, this can be very tedious in files that use many parts of lodash.

Is it possible to achieve the same effect using import in the style of ES6 and Babel DCE Transformer ? For instance:

 import { forEach } from 'lodash'; 

I am suspicious because it imports from the root of the lodash library, and not from a separate function file, as in the previous example.

+5
source share
1 answer

Given that you're probably already using Babel, I think babel-plugin-lodash can do the trick. It can perform conversion 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 @reflog mentioned in the comments, this approach does not work with the lodash chain!

+10
source

Source: https://habr.com/ru/post/1233101/


All Articles