babel配置文件:
- //.babelrc
- {
- "presets": [
- "@babel/preset-env",
- "@babel/preset-react"
- ],
- "plugins": [
- "@babel/plugin-proposal-class-properties",
- [
- "@babel/plugin-transform-runtime",
- {
- "corejs": {
- "version": 3,
- "proposals": true
- },
- "helpers": true,
- "regenerator": true
- }
- ],
- [
- "import",
- {
- "libraryName": "antd"
- },
- "antd"
- ],
- [
- "import",
- {
- "libraryName": "lodash",
- "libraryDirectory": "",
- "camel2DashComponentName": false
- },
- "lodash"
- ]
- ]
- }
业务代码:
- import _ from 'lodash';
-
- //枚举翻译
- valToText = () => {
- const { customeName, useColField, quantOption, children, record, uikey } = this.props;
-
- // 自定义按钮文案
- if (customeName) {
-
- // 使用列字段
- if (useColField && !_.isEmpty(uikey)) {
- return _.get(record, uikey, '');
- }
-
- // 使用数据字典
- if (_.isArray(quantOption) && !_.isEmpty(uikey)) {
- const currentOption = _.find(quantOption, ({ value }) => record[uikey] === value);
- const text = _.get(currentOption, 'name', record[uikey]);
- return text;
- }
- }
-
- return children;
- }
对业务代码打包:
"build": "babel _components --out-dir dist --ignore \"**/*.test.js\" --copy-files",
打包后的文件运行报错:find函数调用报错

对应打包代码:

find函数打印如下:后面括号的_报错
_.find()和[].find,即把_当成了数组处理,所以数组的find函数调用后是(0, _find2.default)([])
(0, _find2.default)(_)
如下其他lodash函数正常,find函数被babel处理polyfill,将find当成了数组的findpolyfill了

修改find函数引入
import _, { find } from 'lodash';
打包后正常:
var _find3 = _interopRequireDefault(require("lodash/find"));
1. plugins运行在presets之前;
2. plugins配置项,按照声明顺序执行,从第一个到最后一个;
3. presets配置项,按照声明逆序执行,从最后一个到第一个(主要是为了确保向后兼容)
stage-x的参数列表请参考:https://github.com/babel/babel/blob/master/packages/babel-preset-stage-0/README.md
babel7中删除了"stage-x"的预设;建议使用env,代替 es2015、es2016、es2017预设
所以上面babelrc中配置,先执行了@babel/plugin-transform-runtime 误将_.find当成了数组处理,之后在按需加载lodash,顺序错误,应该先引入lodash的find之后再执行polyfill,就不会误处理。
- "plugins": [
- "@babel/plugin-proposal-class-properties",
- [
- "import",
- {
- "libraryName": "antd"
- },
- "antd"
- ],
- [
- "import",
- {
- "libraryName": "lodash",
- "libraryDirectory": "",
- "camel2DashComponentName": false
- },
- "lodash"
- ],
- [
- "@babel/plugin-transform-runtime",
- {
- "corejs": {
- "version": 3,
- "proposals": true
- }
- }
- ]
- ]
直接写 import _ from 'lodash'; 或 import { isEqual } from 'lodash'; 引入的是整个 Lodash 包,约 70kb 左右(压缩后)
import isEqual from 'lodash/isEqual'; 引入的单个使用到的文件,约 15kb 左右(压缩后)。
项目开发时,要注意按需加载,减少代码体积,lodash引入问题,新项目推荐使用 lodash-es 包,因为这可以省去 babel 编译的时间。
老项目存在替换成本,可以使用babel-plugin-lodash或上面的babel-plugin-import实现按需加载。