zoukankan      html  css  js  c++  java
  • 深入浅出的webpack4构建工具---webpack+vue+router 按需加载页面(十五)

    1. 为什么需要按需加载?

    对于vue单页应用来讲,我们常见的做法把页面上所有的代码都打包到一个bundle.js文件内,但是随着项目越来越大,文件越来越多的情况下,那么bundle.js文件也会越来越大,文件大的时候会导致打开页面用户体验相对来说会变慢。因此按需加载代码是很有必要的,每次打开某一个页面的时候,只按需加载那个页面的代码,这样的话,项目中其他代码就不会被加载,这样的话,bundle.js文件也不会把所有项目页面文件代码打包进去,文件也不会很大。其他的页面对应的代码第一次都是按需加载的,加载完成后,就会在浏览器缓存中了。

    2. 如何使用webpack+vue+router 实现vue页面按需加载?

    还是和之前一样,在实现功能之前,我们还是看下我们项目中的整个目录架构如下:

    ### 目录结构如下:
    demo1                                       # 工程名
    |   |--- dist                               # 打包后生成的目录文件             
    |   |--- node_modules                       # 所有的依赖包
    |   |--- app
    |   | |---index
    |   | | |-- views                           # 存放所有vue页面文件
    |   | | | |-- home.vue
    |   | | | |-- index.vue
    |   | | | |-- xxx.vue
    |   | | |-- components                      # 存放vue公用的组件
    |   | | |-- app.js                          # vue入口配置文件
    |   | | |-- router.js                       # 路由配置文件
    |   |--- views
    |   | |-- index.html                        # html文件
    |   |--- webpack.config.js                  # webpack配置文件 
    |   |--- .gitignore  
    |   |--- README.md
    |   |--- package.json
    |   |--- .babelrc                           # babel转码文件

    webpack中提供了 require.ensure()来实现页面按需加载。以前我们引入路由的时候都是通过 import 这样的方式引入的,但是使用import引入vue文件它是不会进行页面按需加载的。首先可以看下我们路由页面。如下:

    app/index/router.js 之前代码使用import引入如下:

    import Vue from 'vue';
    import VueRouter from 'vue-router';
    
    // 引入组件 
    import home from './views/home';
    
    import xxx from './views/xxx';
    
    // 告诉 vue 使用 vueRouter
    
    Vue.use(VueRouter);
    
    const routes = [
      {
        path: '/home',
        component: home
      },
      {
        path: '/xxx',
        component: xxx
      },
      {
        path: '*', // 其他没有的页面都重定向到 home页面去
        redirect: '/home'
      }
    ]
    
    var router = new VueRouter({
      routes: routes
    });
    
    export default router;

    如上代码,每一个vue单页面都是使用import引用进来的,它不会进行页面懒加载的,所以在打包的时候都会打包到bundle.js文件内,因此文件会变得越来越大。因此我们需要使用 require.ensure()实现按需加载。

    2.1、学习使用 require.ensure()

    webpack 在编译时,会静态地解析代码中的 require.ensure(),同时将模块添加到一个分开的 chunk 当中。这个新的 chunk 会被 webpack 通过 jsonp 来按需加载。

    基本使用语法如下:require.ensure(dependencies: String[], callback: function(require), chunkName: String);

    参数dependencies:该参数是一个字符串数组,通过这个参数,在所有的回调函数的代码被执行前,我们可以将所有需要用到的模块进行声明。

    参数callback: 当所有的依赖都加载完成后,webpack会执行这个回调函数。require 对象的一个实现会作为一个参数传递给这个回调函数。因此,我们可以进一步 require() 依赖和其它模块提供下一步的执行。

    参数chunkName: chunkName 是提供给这个特定的 require.ensure() 的 chunk 的名称。

    下面我们来看一个demo,在app/index 下新建一个文件夹为js。在js文件夹内分别新建a.js和b.js,代码分别如下:

    a.js 代码如下:

    alert('aaaaaa');

    b.js 代码如下

    alert('bbbbbbb');

    然后入口文件app.js 代码如下:

    require('./js/a');
    require.ensure([], function(require) {
      require('./js/b');
    });

    webpack.config.js 打包如下:

    module.exports = {
      // 入口文件
      entry: {
        main: './app/index/app.js'
      },
      output: {
        filename: process.env.NODE_ENV === 'production' ? '[name].[contenthash].js' : 'bundle.js',
        // 将输出的文件都放在dist目录下
        path: path.resolve(__dirname, 'dist')
      }
    }

    通过执行这个项目的 webpack 构建,我们发现 webpack 创建了2个新的文件束, bundle.js 和 0.bundle.js。如下图所示:

    app.js 和 a.js 被打包进 bundle.js.

    其中 0.bundle.js 代码如下:

    (window.webpackJsonp=window.webpackJsonp||[]).push([[0],{"./app/index/js/b.js":function(b,n){alert("bbbbbbb")}}]);

    bundle.js 代码如下:

    !function(u){function e(e){for(var n,t,r=e[0],o=e[1],a=0,i=[];a<r.length;a++)t=r[a],p[t]&&i.push(p[t][0]),p[t]=0;for(n in o)Object.prototype.hasOwnProperty.call(o,n)&&(u[n]=o[n]);for(l&&l(e);i.length;)i.shift()()}var t={},p={main:0};function c(e){if(t[e])return t[e].exports;var n=t[e]={i:e,l:!1,exports:{}};return u[e].call(n.exports,n,n.exports,c),n.l=!0,n.exports}c.e=function(a){var e=[],t=p[a];if(0!==t)if(t)e.push(t[2]);else{var n=new Promise(function(e,n){t=p[a]=[e,n]});e.push(t[2]=n);var r,o=document.getElementsByTagName("head")[0],i=document.createElement("script");i.charset="utf-8",i.timeout=120,c.nc&&i.setAttribute("nonce",c.nc),i.src=c.p+""+a+".bundle.js",r=function(e){i.onerror=i.onload=null,clearTimeout(u);var n=p[a];if(0!==n){if(n){var t=e&&("load"===e.type?"missing":e.type),r=e&&e.target&&e.target.src,o=new Error("Loading chunk "+a+" failed.
    ("+t+": "+r+")");o.type=t,o.request=r,n[1](o)}p[a]=void 0}};var u=setTimeout(function(){r({type:"timeout",target:i})},12e4);i.onerror=i.onload=r,o.appendChild(i)}return Promise.all(e)},c.m=u,c.c=t,c.d=function(e,n,t){c.o(e,n)||Object.defineProperty(e,n,{enumerable:!0,get:t})},c.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},c.t=function(n,e){if(1&e&&(n=c(n)),8&e)return n;if(4&e&&"object"==typeof n&&n&&n.__esModule)return n;var t=Object.create(null);if(c.r(t),Object.defineProperty(t,"default",{enumerable:!0,value:n}),2&e&&"string"!=typeof n)for(var r in n)c.d(t,r,function(e){return n[e]}.bind(null,r));return t},c.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return c.d(n,"a",n),n},c.o=function(e,n){return Object.prototype.hasOwnProperty.call(e,n)},c.p="",c.oe=function(e){throw e};var n=window.webpackJsonp=window.webpackJsonp||[],r=n.push.bind(n);n.push=e,n=n.slice();for(var o=0;o<n.length;o++)e(n[o]);var l=r;c(c.s="./app/index/app.js")}({"./app/index/app.js":function(e,n,t){t("./app/index/js/a.js"),t.e(0).then(function(e){t("./app/index/js/b.js")}.bind(null,t)).catch(t.oe)},"./app/index/js/a.js":function(e,n){alert("aaaaaa")}});

    如上代码分析可以看到,通过 require.ensure([], function(require) { require('./js/b'); }) 动态加载的b函数代码会单独生成一个0.bundle.js文件,如果页面有多个 require.ensure 这个动态加载文件的话,它就会生成多个xx.bundle.js文件了,因此对于vue路由页面来讲可以使用这种方法来动态加载vue页面了。

    如上webpack.config.js 文件,我们可以再加个配置项 chunkFilename,该配置项,可以指定chunk的名字,如下配置:

    module.exports = {
      // 入口文件
      entry: {
        main: './app/index/app.js'
      },
      output: {
        filename: process.env.NODE_ENV === 'production' ? '[name].[contenthash].js' : 'bundle.js',
        // 将输出的文件都放在dist目录下
        path: path.resolve(__dirname, 'dist'),
        chunkFilename: 'chunks/[name].chunk.js'
      }
    }

    app/index/app.js 代码如下,加了第三个参数, 名字为b:

    require('./js/a');
    require.ensure([], function(require) {
      require('./js/b');
    }, 'b');

    然后会在 dist/chunks 下生成 b.chunk.js, 如下图所示:

    2.2. 在vue-router中使用require.ensure() 方法动态加载不同的vue页面。

    因此我们现在可以在 app/index/router.js 里面如下对vue页面文件进行按需加载了,如下代码:

    import Vue from 'vue';
    import VueRouter from 'vue-router';
    
    // 告诉 vue 使用 vueRouter
    Vue.use(VueRouter);
    
    const routes = [
      {
        path: '/home',
        name: 'home',
        component: resolve => require.ensure([], () => resolve(require('./views/home')), 'home')
      },
      {
        path: '/xxx',
        name: 'xxx',
        // component: resolve => require(['./views/xxx'], resolve)
        component: resolve => require.ensure([], () => resolve(require('./views/xxx')), 'xxx')
      },
      {
        path: '*', // 其他没有的页面都重定向到 home页面去
        redirect: '/home'
      }
    ]
    
    var router = new VueRouter({
      base: '/app/index', // 配置单页应用的基路径
      routes: routes
    });
    
    export default router;

    webpack.config.js 代码配置如下:

    module.exports = {
      // 入口文件
      entry: {
        main: './app/index/app.js'
      },
      output: {
        filename: process.env.NODE_ENV === 'production' ? '[name].[contenthash].js' : 'bundle.js',
        // 将输出的文件都放在dist目录下
        path: path.resolve(__dirname, 'dist'),
        chunkFilename: 'chunks/[name].chunk.js'
      }
    } 

    在dist/chunks 目录下会生成如下文件,如下图所示

    github源码

  • 相关阅读:
    B3
    B2
    b1
    个人作业——软件工程实践总结作业
    Beta 答辩总结
    Beta 冲刺 (7/7)
    Beta 冲刺 (6/7)
    Beta 冲刺 (5/7)
    Beta 冲刺 (4/7)
    Beta 冲刺 (3/7)
  • 原文地址:https://www.cnblogs.com/tugenhua0707/p/9720615.html
Copyright © 2011-2022 走看看