标签: cdn

  • Vue打包优化

    打包优化

    1.异步组件,路由按需加载 (解决首屏加载过慢)

    component: () => import('@/views/Home/index')

    2.排除一些依赖包,将依赖包(不太会变化的包,如Vue、Element UI等)存在cdn上,可以加快打包速度,也可以让不同地域的用户在请求资源时得到更快的响应

    webpack排除打包

    找到 vue.config.js,在configureWebpack配置项中添加externals 选择填入不打包的依赖包

    configureWebpack: {
      ...
      externals: {
        // key(要排除的包名), value(引入的CDN包的全局变量名)
        'vue': 'Vue',
        'element-ui': 'ELEMENT',
        ...
      },
    }

    此时这些包已经被排除打包了,因为缺少这些包,项目无法正常运行,接下来还需要配置CDN

    vue.config.js

    const cdn = {
      css: [
        'https://unpkg.com/element-ui/lib/theme-chalk/index.css' // element-ui css 样式表
      ],
      js: [
        // vue must at first!
        'https://unpkg.com/vue/dist/vue.js', // vuejs
        'https://unpkg.com/element-ui/lib/index.js', // element-ui js
        ...
      ]
    }

    开发环境没有必要使用CDN来引入包,可以通过环境变量来判断是否使用CDN

    const isProduction = process.env.NODE_ENV === 'production' // 判断是否是生产环境
    
    let externals = {}
    let cdn = { css: [], js: [] }
    
    if (isProduction) {
      externals = {
        // key(要排除的包名), value(引入的CDN包的全局变量名)
        'vue': 'Vue',
        'element-ui': 'ELEMENT',
        ...
      }
      cdn = {
        css: [
          'https://unpkg.com/element-ui/lib/theme-chalk/index.css' // element-ui css 样式表
        ],
        js: [
          // vue must at first!
          'https://unpkg.com/vue/dist/vue.js', // vuejs
          'https://unpkg.com/element-ui/lib/index.js', // element-ui js
          ...
        ]
      }
    } 
    
    
    ···
    // 使用externals
    module.exports = {
      configureWebpack: {
      ...
      externals: externals,
     }
    }

    将CDN文件链接注入到模板

    https://cli.vuejs.org/zh/guide/webpack.html#修改插件选项

    chainWebpack(config) {
      // it can improve the speed of the first screen, it is recommended to turn on preload
      config.plugin('preload').tap(() => [
        {
          rel: 'preload',
          // to ignore runtime.js
          // https://github.com/vuejs/vue-cli/blob/dev/packages/@vue/cli-service/lib/config/app.js#L171
          fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
          include: 'initial'
        }
      ])
    
      // 注入cdn变量 (打包时会执行)   
      //https://cli.vuejs.org/zh/guide/webpack.html#修改插件选项
      config.plugin('html').tap(args => {
        args[0].cdn = cdn // 配置cdn给插件
        return args
      })
      ...
    }

    找到 public/index.html

    <head>
      <!-- 引入CSS -->
      <% for(var css of htmlWebpackPlugin.options.cdn.css) { %>
        <link rel="stylesheet" href="<%=css%>">
      <% } %>
    </head>
    
    <!-- 引入JS -->
    <% for(var js of htmlWebpackPlugin.options.cdn.js) { %>
      <script src="<%=js%>"></script>
    <% } %>

    打包

    yarn build