lodash按需加载

lodash提供了不少可用的方法供咱们使用,绝对是一个很好用且用起来驾轻就熟的工具库。可是同时,lodash的体积也不小,咱们项目中使用的大概522K,可能只是使用了几个方法,可是却把整个lodash库引入了。为了吃几条鱼,就承包了整个鱼塘,代价有点大呀!vue

对于这个问题,有几种方案可供选择。node

一.引入单个函数webpack

 lodash整个安装完以后,引用方式: lodash/function 格式,单独引入某个函数,如es6

let _trim= require('lodash/trim') 或者 import trim from 'lodash/trim' web

 或者 lodash 中的每一个函数在 NPM 都有一个单独的发布模块,单独安装并引用部分模块,而后按如下方式引用npm

let _trim= require('lodash.trim') 或者 import trim from 'lodash.trim' json

trim(' 123123 ')安全

二.借助 lodash-webpack-plugin,babel-plugin-lodash插件优化babel

  使用上述两种方式,在使用较多个lodash中方法的状况下,不太美观,且并不方便。那么咱们能够借助于lodash-webpack-plugin,去除未引入的模块,须要和babel-plugin-lodash插件配合使用。相似于webpack的tree-shaking。ide

  1)安装插件:npm i -S lodash-webpack-plugin babel-plugin-lodash

  2)webpack.conf.js中

  var LodashModuleReplacementPlugin = require('lodash-webpack-plugin')

  plugins: [ new LodashModuleReplacementPlugin()]

3).babelrc中配置 "plugins": ["transform-runtime","transform-vue-jsx","lodash"]

  或者在webpack.conf.js的rules配置

{
test: /\.(js|jsx)$/,
loader: 'babel-loader',
exclude: /node_modules/,
include: [resolve('src'), resolve('test')]
options: {plugins: ['lodash']}
}

三.lodash-es结合tree-shaking

lodash-es 是着具有 ES6 模块化的版本,只须要直接引入就能够。

import {isEmpty,forIn, cloneDeep} from 'lodash-es'

tree-shaking的做用,即移除上下文中未引用的代码(dead code)

只有当函数给定输入后,产生相应的输出,且不修改任何外部的东西,才能够安全作shaking的操做

如何使用tree-shaking?

1).确保代码是es6格式,即 export,import

2).package.json中,设置sideEffects

3).确保tree-shaking的函数没有反作用

4).babelrc中设置presets [["env", { "modules": false }]] 禁止转换模块,交由webpack进行模块化处理

5).结合uglifyjs-webpack-plugin

相关文章
相关标签/搜索