Resources
What is lodash-webpack-plugin?
Why should not use lodash-webpack-plugin?
You-Dont-Need-Lodash-Underscore
What is Module Transpilation?
Next.js setup related
Next.js Module Transpilation
Your Lodash Tutorial: How To Import Lodash Libraries
Background
Currently lodash usage in the project leads to huge bundle size
import _ from 'lodash';
Solution 1: replace lodash with lodash-es
Step-by-steps
Remove existing lodash related packages use yarn remove
"lodash": "^4.17.21",
"lodash-webpack-plugin": "^0.11.6",
"babel-plugin-lodash": "^3.3.4",
Remove lodash config from babel plugin
"babel": {
"presets": [
[
"next/babel",
{
"env": {
"corejs": "3",
"useBuiltIns": "entry"
}
}
]
],
"plugins": [
"lodash"
]
},
Update next.config.js
Add "lodash-es" to transpilePackages
, for example,
module.exports = {
transpilePackages: [
...,
'lodash-es'],
}
Errors and solutions
After switching to lodash-es, Jest unit test is executed and an error is reported
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Root cause
Jest does not support ESM
Solution
- Switch back to lodash and tree-shaking by changing the import method, and add eslint rules to consist the use of lodash
Choose this solution
- use babel-jest to only transpile jest unit test codes?
- https://nextjs.org/docs/14/pages/building-your-application/testing/jest
However, this solution does not work
Solution 2: Replace the current lodash import method with the correct one, and add ESlint rules to standardize the correct use of lodash import
Steps
Update the lodash import usage in the project
Change from
import _ from 'lodash';
To
import find from 'lodash/find';
Add ESlint no-restricted-imports for lodash
Make sure your team follows the same way when importing lodash
Add below into eslint config
"no-restricted-imports": [
"error",
{
"paths": [
{
"name": "lodash",
"message": "Import [module] from lodash/[module] instead"
}
],
"patterns": [
{
"group": [
"lodash/set"
],
"message": "Import [module] from lodash/fp/[module] instead"
}
]
}
],
Remove unneeded babel-plugin-lodash
Run yarn remove babel-plugin-lodash
to remove the library.
Remove configuration from Babel config plugin
...
"plugins": [
"lodash"
]
...