This Webpack loader cherry-picks Lodash functions and require them explicitly to reduce the webpack bundle size.
npm install lodash-loader
Add this to your webpack.config.js to apply the logic to your .js
files.
const createLodashAliases = require('lodash-loader').createLodashAliases;
module.exports = {
...
module: {
rules: [
{ test: /\.js$/, loader: "babel-loader!lodash-loader" }
]
},
resolve: {
alias: createLodashAliases()
}
...
};
Add this to your webpack.config.js to apply the logic to your .ts
files.
const createLodashAliases = require('lodash-loader').createLodashAliases;
module.exports = {
...
module: {
rules: [
{ test: /\.ts$/, loader: "ts-loader!lodash-loader" }
]
},
resolve: {
alias: createLodashAliases()
}
...
};
Note: This loader has to run before babel-loader or ts-loader.
This loader changes your code to explicitly reference single lodash functions instead of import the whole lodash library.
Example:
import * as _ from "lodash";
export class Main {
public myMethod() {
_.each([], (e) => {
console.log(e);
});
_.isArray({});
_.filter([], { name: "joe" });
}
}
This is modified to:
import * as _each from "lodash/each";
import * as _isArray from "lodash/isArray";
import * as _filter from "lodash/filter";
export class Main {
public myMethod() {
_each([], (e) => {
console.log(e);
});
_isArray({});
_filter([], { name: "joe" });
}
}
This works only if you import the lodash library in your code. Do NOT use lodash from browsers window
variable. The import
has to be a valid ES2015 or TypeScript-Import:
import _ from "lodash";
import * as _ from "lodash";
Function chaining is NOT supported at the moment. The same applies to lodash/fp
functions.
You can configure a query parameter called importMode
to decide the destination import format:
Parameter | Mandatory | Data type | Possible values | Default value |
---|---|---|---|---|
importMode |
False | String | legacy,es2015,es2015-default,commonjs | legacy |
This are analysis of a webpack build from a medium-sized web-project. There were 11 different functions in use.
Analyse | Library |
---|---|
Underscore 1.8.3 (51,7k) | |
Lodash 4.17.4 (full) (526,9k) | |
Lodash 4.17.4 (optimized) (140,8k) |