3

性能优化

懒加载

  • 代码模块化
  • import()

代码模块化

  1. es6
  2. commonjs

动态导入

  1. import=>promise=>fullfillded/failed
  2. 构建=>chunk
  3. 运行=>dynamic add script
const xxx =await import('../xxx')
魔法注释
  1. webpackChunkName:指定同一webpackChunkName会被合并成同一模块,打包合并到同一js文件const LoginPage = import( /* webpackChunkName: "login" */ '../pages/login' )
  2. webpackMode:指定加载模块的方式——lazy、lazy-once、eager

    • lazy:懒加载目标模块,打包构建时会分割出1个独立的chunk,只在import()执行时才发起请求加载相应产物文件 lazy-once async function getIcon(name) { return import( /* webpackMode: "lazy-once" */ `../image/${name}.svg` ) } const HomeIcon = getIcon('home') const BlogIcon = await getIcon('blog')
    • lazy-once:会把所有动态路径匹配的模块文件合并为1个chunk,打包成1个产物文件,执行import(),复用同一文件
    • eager:目标模块打包构建不会产生额外的chunk,也就不会有产物文件,而是会把对应模块的代码合并进已有的chunk中。 const LoginPage = import( /* webpackMode: "eager" */ '../pages/login' )

懒加载不生效问题

  1. 修改为懒加载的模块,未修改完全,有遗留
  2. splitchunk.cacheGroup,目标命中懒加载模块,all修改为initial,即该模块仅包含直接导入的模块,动态导入的模块将被排除

DllPlugin && DllRefrencePlugin (基于vuecli)

//新建webpack.dll.config.plugin
const path = require('path')
const webpack = require('webpack');
const package = require('./package.json')
let dependencies = Object.keys(package.dependencies) || []
//这些都要报错 ,可以自己配loader ,这边直接排除
let excludes =['screenfull','vue','patch-package','increase-memory-limit','normalize.css','flex.css','animate.css','@fullcalendar/daygrid', "@fullcalendar/bootstrap","@fullcalendar/core","@fullcalendar/list","@fullcalendar/timegrid","@fullcalendar/vue"]
//如果使用了chrome的vue-devtool,那打包的时候把vue也排除掉,因为压缩过的vue是不能使用vue-devtool的
dependencies = dependencies.length > 0 ? dependencies.filter(item =>!excludes.includes(item)) : []
module.exports = {
  entry: {
    vendor: dependencies  // 需要预编译的依赖库
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
        'vue$': 'vue/dist/vue.esm.js',
    }
  },
  output: {
    path: path.join(__dirname, 'public'),
    filename: 'dll.[name]_[hash:6].js',
    library: '[name]_[hash:6]'
  },
  plugins: [
    new webpack.DllPlugin({
      path: path.join(__dirname, 'public', '[name]-manifest.json'),
      name: '[name]_[hash:6]'
    }),
  ]
};
//dll.config配置完成后执行ebpack --config ./webpack.dll.config.js 
//可在package.json配置执行命令
"dll": "webpack --config ./webpack.dll.config.js"


//vue.config.js
configNew.plugins.push(
    new webpack.DllReferencePlugin({
        context: process.cwd(),
        manifest:require('./public/vendor-manifest.json'),
    })
)

//index.html
<script src="./dll.vendor_xxxx.js"></script>
  • 碰到的问题

    • el-table渲染失败,通过查看element issue ——在dll.config文件中配置alias 和自己vue.config.js的alias需要保持一致
    •  //在el-table中引入了vue ,项目中依赖的是'vue/dist/vue.esm.js,elment 依赖的是//vue.runtime.esm.js
       resolve: {
          extensions: ['.js', '.vue', '.json'],
          alias: {
              'vue$': 'vue/dist/vue.esm.js',
          }

mmm9foJb
1 声望3 粉丝

« 上一篇
lowdb