<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Keep moving</title>
    <description>blog &amp; blog theme🤘</description>
    <link>https://heiguagua.github.io/</link>
    <atom:link href="https://heiguagua.github.io/feed.xml" rel="self" type="application/rss+xml"/>
    <pubDate>Wed, 29 Apr 2020 07:52:04 +0000</pubDate>
    <lastBuildDate>Wed, 29 Apr 2020 07:52:04 +0000</lastBuildDate>
    <generator>Jekyll v3.8.5</generator>
    
      <item>
        <title>JavaScript webpack相关</title>
        <description>&lt;h3 id=&quot;模块化的演进过程&quot;&gt;模块化的演进过程&lt;/h3&gt;
相信很多人对 webpack 都不陌生，现在流行的前端框架都广泛使用了 webpack，但是我们在开发过程中几乎没怎么用到，所以难免会产生疑问，有没有必要学习 webpack ？答案是肯定的！&lt;br /&gt;
随着互联网的发展，前端技术标准发生了巨大的变化。早期的前端技术标准没有预料到前端会有今天这样的规模，所以在设计上有很多缺陷，导致我们在实现前端模块化时会遇到很多问题。虽然说大部分问题都已经被一些标准或工具解决了，但在这个标准的演进过程中有很多东西值得我们思考和学习。

&lt;h4 id=&quot;1文件划分方式&quot;&gt;1、文件划分方式&lt;/h4&gt;
最早我们基于文件划分的方式实现模块化，具体做法是将每个功能模块及相关数据和状态单独放在不同的js文件中，约定每个文件是一个独立的模块。使用时一个script标签对应一个模块，然后直接调用模块中的成员（变量/函数）。
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// moduleA.js
function foo() {
  console.log('moduleA#foo');
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
  &amp;lt;meta charset=&quot;UTF-8&quot;&amp;gt;
  &amp;lt;title&amp;gt;Stage 1&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
  &amp;lt;script src=&quot;moduleA.js&quot;&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;script&amp;gt;
    // 直接使用全局成员
    foo() // 可能存在命名冲突
  &amp;lt;/script&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
缺点：
&lt;ul&gt;
  &lt;li&gt;模块直接作用于全局，大量模块成员对全局作用域造成污染&lt;/li&gt;
  &lt;li&gt;没有私有控件，模块的成员都可能在模块外部被访问或者修改&lt;/li&gt;
  &lt;li&gt;模块增多，很容易产生命名冲突&lt;/li&gt;
  &lt;li&gt;模块间的依赖关系不易管理&lt;br /&gt;
一旦项目规模变大，这种靠约定实现的模块化会暴露出种种问题。&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;2命名空间方式&quot;&gt;2、命名空间方式&lt;/h4&gt;
这个阶段约定每个模块只暴露一个全局对象，所有模块成员都挂载到这个全局对象中。具体做法就是将每个模块包裹为一个全局对象的形式，这种方式就像是为模块内的成员增加了“命名空间”，所以称之为命名空间方式。
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// moduleA.js  
window.moduleA = {
  method1: function () {
    console.log('moduleA#foo')
  }
}

// moduleB.js  
window.moduleB = {
  data: 'something'
  method1: function () {
    console.log('moduleB#method1')
  }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
  &amp;lt;meta charset=&quot;UTF-8&quot;&amp;gt;
  &amp;lt;title&amp;gt;Stage 2&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
  &amp;lt;script src=&quot;module-a.js&quot;&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;script src=&quot;module-b.js&quot;&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;script&amp;gt;
    moduleA.method1()
    moduleB.method1()
    // 模块成员依然可以被修改
    moduleA.data = 'foo'
  &amp;lt;/script&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
这种方式只是解决了命名冲突的问题，但是其他问题依旧存在。

&lt;h4 id=&quot;3iife&quot;&gt;3、IIFE&lt;/h4&gt;
使用立即执行函数表达式（IIFE，Immediately-Invoked Function Expression）为模块提供私有控件，具体做法是将每个模块成员都放在一个立即执行函数所形成的私有作用域中，对于需要暴露给外部的成员，通过挂到全局对象上的方式实现。
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// module-a.js
;(function () {
  var name = 'module-a'

  function method1 () {
    console.log(name + '#method1')
  }

  window.moduleA = {
    method1: method1
  }
})()  

// module-b.js
;(function () {
  var name = 'module-b'

  function method1 () {
    console.log(name + '#method1')
  }

  window.moduleB = {
    method1: method1
  }
})()
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
这种方式带来了私有成员的概念，私有成员只能在模块成员内通过闭包的形式访问，这就解决了前面所提到的全局作用域污染和命名冲突的问题。

&lt;h4 id=&quot;4iife-依赖参数&quot;&gt;4、IIFE 依赖参数&lt;/h4&gt;
在 IIFE 的基础上，我们还可以利用IIFE参数作为依赖声明使用，使得模块间的依赖关系更加明显。
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// module-a.js
;(function ($) { // 通过参数明显表明这个模块的依赖
  var name = 'module-a'

  function method1 () {
    console.log(name + '#method1')
    $('body').animate({ margin: '200px' })
  }

  window.moduleA = {
    method1: method1
  }
})(jQuery)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;h4 id=&quot;模块加载的问题&quot;&gt;模块加载的问题&lt;/h4&gt;
以上4个阶段是早期的开发者在没有工具和规范的情况下对模块化的落地方式，这些方式解决了很多在前端领域实现模块化的问题，但是仍然存在一些问题。
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
&amp;lt;head&amp;gt;
  &amp;lt;title&amp;gt;Evolution&amp;lt;/title&amp;gt;
&amp;lt;/head&amp;gt;
&amp;lt;body&amp;gt;
  &amp;lt;script src=&quot;https://unpkg.com/jquery&quot;&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;script src=&quot;module-a.js&quot;&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;script src=&quot;module-b.js&quot;&amp;gt;&amp;lt;/script&amp;gt;
  &amp;lt;script&amp;gt;
    moduleA.method1()
    moduleB.method1()
  &amp;lt;/script&amp;gt;
&amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
最明显的问题就是：模块的加载。我们都是通过script标签的方式直接在页面中引入的这些模块，意味着这些模块的加载不受代码的控制，时间久了维护起来会十分麻烦。

更为理想的方式应该是在页面中引入一个入口js文件，其余用到的模块可以通过代码控制，&lt;strong&gt;按需加载&lt;/strong&gt;进来。

&lt;h4 id=&quot;模块化规范的出现&quot;&gt;模块化规范的出现&lt;/h4&gt;
为了统一不同开发者、不同项目之间的差异，我们需要制定一个行业标准去规范模块化的实现方式。&lt;br /&gt;
&lt;strong&gt;CommonJS&lt;/strong&gt;&lt;br /&gt;
提到模块化规范，最先想到的可能就是 CommonJs 规范了，它是 Node.js 中所遵循的模块规范&lt;br /&gt;
&lt;strong&gt;module 对象&lt;/strong&gt;&lt;br /&gt;
node 提供了一个 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Module&lt;/code&gt; 构造函数，所有的模块都是 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Module&lt;/code&gt; 的实例。每个模块都有一个 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;module&lt;/code&gt; 对象，代表当前模块。&lt;br /&gt;
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;module.exports &lt;/code&gt;是 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;module&lt;/code&gt; 对象重要的属性，表示当前模块对外输出的接口，其他文件加载该模块，实际上就是读取的 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;module.exports&lt;/code&gt; 变量。&lt;br /&gt;
&lt;strong&gt;exports 变量&lt;/strong&gt;&lt;br /&gt;
为了方便，node为每个模块提供了exports变量，指向 module.exports。这相当于在每个模块的头部，都有一行这样的代码：

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;var exports = module.exports;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
对外输出
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// a.js
exports.msg = 'hello';

exports.say = function(p) {
    return p;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;strong&gt;require 命令&lt;/strong&gt;&lt;br /&gt;
node 内置的 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;require&lt;/code&gt; 命令用来加载模块文件。&lt;br /&gt;
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;require&lt;/code&gt; 命令的基本功能就是，读入并执行一个 javascript 文件，然后返回该模块的 exports 对象。

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;var say = require('a.js');

say('hello);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
该规范有以下特点：
&lt;ul&gt;
  &lt;li&gt;
    每个文件就是一个模块，有自己的作用域，文件里面定义的变量、函数等都是私有的，对其他文件不可见。
  &lt;/li&gt;
  &lt;li&gt;
    服务器端广泛使用的模块化加载机制，以为模块一般都存在本地，不需要考虑网络等因素，所以为同步加载。
  &lt;/li&gt;
  &lt;li&gt;
    模块加载一次就被缓存起来，再次加载直接读取缓存。
  &lt;/li&gt;
  &lt;li&gt;
    模块加载的顺序按照其在代码中出现的顺序加载。&lt;br /&gt;
这种方式在服务器端使用没有问题，但是要在浏览器端使用同步的方式加载模块，就会引起大量的同步模式请求，导致运行效率大大降低。
  &lt;/li&gt;
&lt;/ul&gt;

&lt;strong&gt;AMD&lt;/strong&gt;
所以早期并没有直接选择 CommonJS 规范，而是专门针对浏览器重新设计了一个规范，叫做 AMD (Asynchronous Module Definition) 规范，即异步模块定义规范。最出名的实现库就是 Require.js。&lt;br /&gt;
  在 AMD 规范中约定通过 define() 函数定义模块。

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// AMD 定义一个模块
define(['jquery', './module.js'], function($, module) {
  return {
    method1: function() {
      module();
      ...
    },
    ...
  }
})
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
除此之外，Require.js 还提供了一个 require() 函数用于加载模块，用法与 define() 函数类似，区别在于 require() 只能用来载入模块，define() 可以定义模块。
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;require(['./module.js'], function(module) {
  module.method();
})
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
目前绝大多数第三方库都支持 AMD 规范，但是它使用起来相对复杂，随着应用规模扩大，模块划分更为细致时，会出现一个页面请求次数过多的情况。

&lt;h4 id=&quot;模块化规范标准规范&quot;&gt;模块化规范标准规范&lt;/h4&gt;
随着技术的发展， JavaScript 的标准逐渐走向完善，而且对前端模块化规范的最佳实践也基本实现了统一。
&lt;ul&gt;
  &lt;li&gt;在 Node.js 环境中，遵循 CommonJS 规范来组织模块。&lt;/li&gt;
  &lt;li&gt;浏览器环境中，遵循 ES Modules 规范。&lt;br /&gt;
&lt;strong&gt;ES Modules&lt;/strong&gt;&lt;br /&gt;
ES Modules 是 ECMAScript 2015（ES6）中才定义的模块系统，在这个标准刚推出的时候，几乎所有主流的浏览器都不支持，但是随着 Webpack 等一系列打包工具的流行，这一规范才开始被逐渐普及。&lt;br /&gt;
经过5年的迭代，ES Modules 已发展成为目前最主流的前端模块化标准，它在语言层面实现了模块化，并且目前绝大多数主流浏览器已经开始能够原生支持 ES Modules 特性了，因此如何在不同的环境中更好的使用ES Modules 是我们要重点考虑的问题。
    &lt;h4 id=&quot;模块化打包工具的出现&quot;&gt;模块化打包工具的出现&lt;/h4&gt;
    模块化可以帮助我们解决复杂应用开发过程中的代码组织问题，但是随着模块化思想的引入，前端应用又会产生一些新的问题：
  &lt;/li&gt;
  &lt;li&gt;在无法保证用户浏览器使用情况下，我们必须要解决兼容性问题。&lt;/li&gt;
  &lt;li&gt;模块化的方式划分出来的模块文件过多，每个文件都需要单独从服务器请求。零散的模块导致浏览器发送网络请求频繁，影响工作效率。&lt;/li&gt;
  &lt;li&gt;在实际的前端应用开发过程中不仅仅只有 JavaScript 需要模块化， HTML 和 CSS 也会面临需要被模块化的问题。这些文件都应该看做是前端应用中的一个模块。&lt;br /&gt;
对于开发过程而言，模块化肯定是必须的，所以我们需要在这个基础上引入更好的方案或者工具来解决上面这些问题，让我们继续享受模块化在开发过程给我们带来的享受，同时又不必担心模块化对生产环境产生的影响。&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;webpack&quot;&gt;Webpack&lt;/h4&gt;
前端模块化的进程和最终统一的 ES Modules 标准都是我们深入学习 Webpack 前必须要掌握的只是，同时也是作为前端开发必不可少的基础储备。&lt;br /&gt;
Webpack 发展到今天，已经非常强大了，从一个“打包工具”发展到今天的整个前端项目的“构建系统”，它的初衷“模块化解决方案”透露出的“模块化思想”有很多值得我们学习思考的地方。

&lt;h3 id=&quot;babel&quot;&gt;Babel&lt;/h3&gt;
&lt;h4 id=&quot;babel-产生的背景&quot;&gt;Babel 产生的背景&lt;/h4&gt;
javascript 是 web 语言，不同浏览器都会有不同的 javascript 解释器对其进行解释编译运行。由于 js 被广泛接受，随后又有 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ECMA (European Computer Manufacturers Association 欧洲计算机制造商协会)&lt;/code&gt;对其进行规范管理，js 所遵循的规范也叫 ECMAScript 或者 ES。&lt;br /&gt;
其中第5版也就是 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ES5&lt;/code&gt; 于2009年定稿，目前主流浏览器都全部支持。&lt;br /&gt;
第6个版本 ES2015 即 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ES6&lt;/code&gt; ，在2015年定稿，目前主流浏览器并不是全部支持。&lt;br /&gt;
还有ES7、ES8 在原来的基础上，增加了一些新功能。

如果我们希望立刻就能使用 ES6/ES7/ESNext…，但同时我们也希望我们的代码能在主流浏览器或者node中正常运行，那这就是 Babel 产生的原因了。

简单来说，Babel就是把JavaScript 中 ES6/ES7/ESNext等新语法转换为 ES5（也可以转换为更低的规范，但目前 ES5 规范已经足以覆盖绝大部分主流浏览器，因此可以认为转到 ES5 是一个安全且流行的做法），让低端运行环境如浏览器或者node能认识并执行的工具。

我们可以将babel理解为一个转译器 transpiler 而不是编译器 compiler 更准确，因为它只是把同种语言的高版本规则翻译成低版本规则，但是和编译器类似，它也分为3个阶段，&lt;strong&gt;parsing&lt;/strong&gt;、 &lt;strong&gt;transforming&lt;/strong&gt;、&lt;strong&gt;generating&lt;/strong&gt;，以 ES6 转译为 ES5 为例，babel转译的具体过程如下：

&lt;img src=&quot;./assets/babel.png&quot; alt=&quot;babel&quot; /&gt;

&lt;h4 id=&quot;关键概念&quot;&gt;关键概念&lt;/h4&gt;
&lt;strong&gt;plugins&lt;/strong&gt;&lt;br /&gt;
Babel 本身不具备任何转化功能，它通过配置 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;plugins&lt;/code&gt; 来对不同的语法特性做转译，主要作用于第二个阶段 &lt;strong&gt;transforming&lt;/strong&gt;。&lt;br /&gt;
&lt;strong&gt;presets&lt;/strong&gt;&lt;br /&gt;
由于不同的语法特性特别多，那么对应的 babel plugin 也会特别多，如果选择手动添加并安装会非常繁琐且不方便管理，为了解决这个问题，babel 提供了一组插件集合 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;presets&lt;/code&gt;，避免了重复定义和安装。&lt;br /&gt;
1、&lt;strong&gt;babel-presest-env&lt;/strong&gt; &lt;br /&gt;
比如我们需要转换 ES6 语法，可以再 .babelrc 的 plugins 中引入插件： es2015-arrow-functions、es2015-block-scoped-function 等等不同作用的 plugin：

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// .babelrc
{
  &quot;plugins&quot;: [
    &quot;es2015-arrow-functions&quot;,
    &quot;es2015-block-scoped-functions&quot;,
    // ...
  ]
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
但是随着需要转换的语法变多，plugin 也相应增多，不便于维护，所以为了方便 Babel 团队将同属 ES2015 的 transform plugins 集合到了 &lt;strong&gt;babel-preset-es2015&lt;/strong&gt; 的 Preset 中，这样我们只需要在 .babelrc 的 presets 引入一个 ES2015 就可以全部支持 ES2015 语法了。
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// .babelrc
{
  &quot;presets&quot;: [
    &quot;es2015&quot;
  ]
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

随着时间推移，可能会有更多版本的插件，如 babel-preset-es2020,…等等，因此 &lt;strong&gt;babel-preset-env&lt;/strong&gt; 出现了，它类似于 &lt;strong&gt;babel-preset-latest&lt;/strong&gt; ，会根据目标环境来进行转译。
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;{
  &quot;presets&quot;: ['env']
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;strong&gt;polyfill&lt;/strong&gt;&lt;br /&gt;
Babel 默认只转换 JavaScript 语法，而不转换新的 API，如 Iterator、Set、Maps、Symbol、Promise等全局对象。以及一些在全局对象上的方法（如 Object.assign）等都不会转码。如果想让这些全局对象或API就需要使用 babel-polyfill 来转换。
</description>
        <pubDate>Tue, 28 Apr 2020 00:00:00 +0000</pubDate>
        <link>https://heiguagua.github.io/2020/04/28/JavaScript%E6%A8%A1%E5%9D%97%E5%8C%96%E6%BC%94%E8%BF%9B%E8%BF%87%E7%A8%8B/</link>
        <guid isPermaLink="true">https://heiguagua.github.io/2020/04/28/JavaScript%E6%A8%A1%E5%9D%97%E5%8C%96%E6%BC%94%E8%BF%9B%E8%BF%87%E7%A8%8B/</guid>
        
        <category>JavaScript</category>
        
        <category>webpack</category>
        
        
        <category>Web</category>
        
      </item>
    
      <item>
        <title>模块化之CommonJS、ES6、Babel、Webpack的纠葛</title>
        <description>&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#1commonjs-和-es6的关系&quot; id=&quot;markdown-toc-1commonjs-和-es6的关系&quot;&gt;1、CommonJS 和 ES6的关系&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#commonjs&quot; id=&quot;markdown-toc-commonjs&quot;&gt;CommonJS&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href=&quot;#2babel&quot; id=&quot;markdown-toc-2babel&quot;&gt;2、Babel&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#babel产生的背景&quot; id=&quot;markdown-toc-babel产生的背景&quot;&gt;Babel产生的背景&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#关键概念&quot; id=&quot;markdown-toc-关键概念&quot;&gt;关键概念&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#babel的使用方法&quot; id=&quot;markdown-toc-babel的使用方法&quot;&gt;Babel的使用方法&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;1commonjs-和-es6的关系&quot;&gt;1、CommonJS 和 ES6的关系&lt;/h2&gt;
&lt;h3 id=&quot;commonjs&quot;&gt;CommonJS&lt;/h3&gt;
&lt;strong&gt;同步加载模块、NodeJS&lt;/strong&gt;
&lt;ul&gt;
  &lt;li&gt;每个文件就是一个模块，有自己的作用域，文件里面定义的变量、函数等都是私有的，对其他文件不可见。&lt;/li&gt;
  &lt;li&gt;服务器端广泛使用的模块化加载机制，以为模块一般都存在本地，不需要考虑网络等因素，所以为同步加载。&lt;/li&gt;
  &lt;li&gt;模块加载一次就被缓存起来，再次加载直接读取缓存。&lt;/li&gt;
  &lt;li&gt;模块加载的顺序按照其在代码中出现的顺序加载。&lt;/li&gt;
&lt;/ul&gt;

&lt;strong&gt;module 对象&lt;/strong&gt;&lt;br /&gt;
node 提供了一个 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Module&lt;/code&gt; 构造函数，所有的模块都是 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Module&lt;/code&gt; 的实例。每个模块都有一个 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;module&lt;/code&gt; 对象，代表当前模块。&lt;br /&gt;
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;module.exports &lt;/code&gt;是 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;module&lt;/code&gt; 对象重要的属性，表示当前模块对外输出的接口，其他文件加载该模块，实际上就是读取的 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;module.exports&lt;/code&gt; 变量。&lt;br /&gt;
&lt;strong&gt;exports 变量&lt;/strong&gt;&lt;br /&gt;
为了方便，node为每个模块提供了exports变量，指向 module.exports。这相当于在每个模块的头部，都有一行这样的代码：
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;var exports = module.exports;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
对外输出
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// a.js
exports.msg = 'hello';

exports.say = function(p) {
    return p;
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
注意： 不能直接将 exports 变量指向一个值，因为这相当于切断了 exports 和 module.exports 的联系。 &lt;br /&gt;
&lt;strong&gt;require 命令&lt;/strong&gt;&lt;br /&gt;
node 内置的 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;require&lt;/code&gt; 命令用来加载模块文件。&lt;br /&gt;
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;require&lt;/code&gt; 命令的基本功能就是，读入并执行一个 javascript 文件，然后返回该模块的 exports 对象。
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;var say = require('a.js');

say('hello);
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;h2 id=&quot;2babel&quot;&gt;2、Babel&lt;/h2&gt;
&lt;h3 id=&quot;babel产生的背景&quot;&gt;Babel产生的背景&lt;/h3&gt;
javascript 是 web 语言，不同浏览器都会有不同的 javascript 解释器对其进行解释编译运行。由于 js 被广泛接受，随后又有 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ECMA (European Computer Manufacturers Association 欧洲计算机制造商协会)&lt;/code&gt;对其进行规范管理，js 所遵循的规范也叫 ECMAScript 或者 ES。&lt;br /&gt;
其中第5版也就是 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ES5&lt;/code&gt; 于2009年定稿，目前主流浏览器都全部支持。&lt;br /&gt;
第6个版本ES2015 即 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ES6&lt;/code&gt; ，在2015年定稿，目前主流浏览器并不是全部支持。&lt;br /&gt;
还有ES7、ES8 在原来的基础上，增加了一些新功能。

如果我们希望立刻就能使用 ES6/ES7/ESNext…，但同时我们也希望我们的代码能在主流浏览器或者node中正常运行，那这就是 Babel 产生的原因了。

简单来说，Babel就是把JavaScript 中 ES6/ES7/ESNext等新语法转换为ES5（也可以转换为更低的规范，但目前 ES5 规范已经足以覆盖绝大部分主流浏览器，因此可以认为转到 ES5 是一个安全且流行的做法），让低端运行环境如浏览器或者node能认识并执行的工具。

我们可以将babel理解为一个转译器 transpiler 而不是编译器 compiler 更准确，因为它只是把同种语言的高版本规则翻译成低版本规则，但是和编译器类似，它也分为3个阶段，&lt;strong&gt;parsing&lt;/strong&gt;、 &lt;strong&gt;transforming&lt;/strong&gt;、&lt;strong&gt;generating&lt;/strong&gt;，以 ES6 转译为 ES5 为例，babel转译的具体过程如下：

&lt;img src=&quot;./assets/babel.png&quot; alt=&quot;babel&quot; /&gt;

&lt;h3 id=&quot;关键概念&quot;&gt;关键概念&lt;/h3&gt;
&lt;strong&gt;plugins&lt;/strong&gt;&lt;br /&gt;
Babel 本身不具备任何转化功能，它通过配置 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;plugins&lt;/code&gt; 来对不同的语法特性做转译，主要作用于第二个阶段 &lt;strong&gt;transforming&lt;/strong&gt;。&lt;br /&gt;
&lt;strong&gt;presets&lt;/strong&gt;&lt;br /&gt;
由于不同的语法特性特别多，那么对应的babel plugin也会特别多，如果选择手动添加并安装会非常繁琐且不方便管理，为了解决这个问题，babel 提供了一组插件集合 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;presets&lt;/code&gt;，避免了重复定义和安装。&lt;br /&gt;
1、&lt;strong&gt;babel-presest-env&lt;/strong&gt; &lt;br /&gt;
比如我们需要转换 es6 语法，可以再 .babelrc 的 plugins 中引入插件： es2015-arrow-functions、es2015-block-scoped-function 等等不同作用的 plugin：
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// .babelrc
{
  &quot;plugins&quot;: [
    &quot;es2015-arrow-functions&quot;,
    &quot;es2015-block-scoped-functions&quot;,
    // ...
  ]
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
但是随着需要转换的语法变多，plugin 也相应增多，不便于维护，所以为了方便 Babel 团队将同属 ES2015 的 transform plugins 集合到了 &lt;strong&gt;babel-preset-es2015&lt;/strong&gt; 的 Preset 中，这样我们只需要在 .babelrc 的 presets 引入一个 ES2015 就可以全部支持 ES2015 语法了。
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// .babelrc
{
  &quot;presets&quot;: [
    &quot;es2015&quot;
  ]
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

随着时间推移，可能会有更多版本的插件，如 babel-preset-es2020,…等等，因此 &lt;strong&gt;babel-preset-env&lt;/strong&gt; 出现了，它类似于 &lt;strong&gt;babel-preset-latest&lt;/strong&gt; ，会根据目标环境来进行转译。
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;{
  &quot;presets&quot;: ['env']
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;strong&gt;polyfill&lt;/strong&gt;&lt;br /&gt;
Babel 默认只转换 JavaScript 语法，而不转换新的 API，如 Iterator、Set、Maps、Symbol、Promise等全局对象。以及一些在全局对象上的方法（如 Object.assign）等都不会转码。如果想让这些全局对象或API就需要使用 babel-polyfill 来转换。

&lt;h3 id=&quot;babel的使用方法&quot;&gt;Babel的使用方法&lt;/h3&gt;
一共有以下三种方式：&lt;br /&gt;
1、&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;standalone script&lt;/code&gt;，单体文件，最简单快捷的方式，通过script tag 来引用 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;babel-standalong&lt;/code&gt; package。
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;lt;script
  src=&quot;https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.18.1/babel.min.js&quot;
&amp;gt;&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
引入后，babel就会自动将任何以 text/babel 为 type 的 script 进行解析。&lt;br /&gt;
2、命令行（cli），多见于 package.json 中的某条命令。&lt;br /&gt;
3、构建工具插件（webpack 的 babel-loader、rollup 的 rollup-plugin-babel）。
</description>
        <pubDate>Mon, 13 Apr 2020 00:00:00 +0000</pubDate>
        <link>https://heiguagua.github.io/2020/04/13/%E5%86%8D%E8%B0%88%E6%A8%A1%E5%9D%97%E5%8C%96%E4%B9%8BCommonJS-ES6-Babel-Webpack%E9%97%B4%E7%9A%84%E5%A4%9A%E8%A7%92%E5%85%B3%E7%B3%BB/</link>
        <guid isPermaLink="true">https://heiguagua.github.io/2020/04/13/%E5%86%8D%E8%B0%88%E6%A8%A1%E5%9D%97%E5%8C%96%E4%B9%8BCommonJS-ES6-Babel-Webpack%E9%97%B4%E7%9A%84%E5%A4%9A%E8%A7%92%E5%85%B3%E7%B3%BB/</guid>
        
        <category>CommonJS</category>
        
        <category>ES6</category>
        
        <category>Babel</category>
        
        <category>Webpack</category>
        
        
        <category>Web</category>
        
      </item>
    
      <item>
        <title>webpack相关</title>
        <description>&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#webpack静态资源体积分析与总结&quot; id=&quot;markdown-toc-webpack静态资源体积分析与总结&quot;&gt;Webpack静态资源体积分析与总结&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#webpack内置分析工具&quot; id=&quot;markdown-toc-webpack内置分析工具&quot;&gt;webpack内置分析工具&lt;/a&gt;        &lt;ul&gt;
          &lt;li&gt;&lt;a href=&quot;#1-stats&quot; id=&quot;markdown-toc-1-stats&quot;&gt;1. &lt;strong&gt;stats&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#2-可视化构建分析&quot; id=&quot;markdown-toc-2-可视化构建分析&quot;&gt;2. 可视化构建分析&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#3-report&quot; id=&quot;markdown-toc-3-report&quot;&gt;3. –report&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#webpack打包资源体积优化&quot; id=&quot;markdown-toc-webpack打包资源体积优化&quot;&gt;Webpack打包资源体积优化&lt;/a&gt;        &lt;ul&gt;
          &lt;li&gt;&lt;a href=&quot;#1-打包拆分策略&quot; id=&quot;markdown-toc-1-打包拆分策略&quot;&gt;1. 打包拆分策略&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#2-按需引入&quot; id=&quot;markdown-toc-2-按需引入&quot;&gt;2. 按需引入&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#3-压缩混淆&quot; id=&quot;markdown-toc-3-压缩混淆&quot;&gt;3. 压缩混淆&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#4-图片压缩&quot; id=&quot;markdown-toc-4-图片压缩&quot;&gt;4. 图片压缩&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#5-开启gzip&quot; id=&quot;markdown-toc-5-开启gzip&quot;&gt;5. 开启Gzip&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#6-tree-shaking&quot; id=&quot;markdown-toc-6-tree-shaking&quot;&gt;6. Tree-Shaking&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#7-公共文件提取&quot; id=&quot;markdown-toc-7-公共文件提取&quot;&gt;7. 公共文件提取&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#其他建议&quot; id=&quot;markdown-toc-其他建议&quot;&gt;其他建议&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#代码分割--optimizationsplitchunks&quot; id=&quot;markdown-toc-代码分割--optimizationsplitchunks&quot;&gt;代码分割 &amp;amp; &lt;strong&gt;optimization.splitChunks&lt;/strong&gt;&lt;/a&gt;        &lt;ul&gt;
          &lt;li&gt;&lt;a href=&quot;#代码分割的本质&quot; id=&quot;markdown-toc-代码分割的本质&quot;&gt;代码分割的本质&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#prefetch--preload&quot; id=&quot;markdown-toc-prefetch--preload&quot;&gt;prefetch &amp;amp; preload&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#典型案例&quot; id=&quot;markdown-toc-典型案例&quot;&gt;典型案例&lt;/a&gt;        &lt;ul&gt;
          &lt;li&gt;&lt;a href=&quot;#1首屏加载优化&quot; id=&quot;markdown-toc-1首屏加载优化&quot;&gt;1、首屏加载优化&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h2 id=&quot;webpack静态资源体积分析与总结&quot;&gt;Webpack静态资源体积分析与总结&lt;/h2&gt;
&lt;strong&gt;前言&lt;/strong&gt;&lt;br /&gt;
webpack目前已更新至 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;4.41.2&lt;/code&gt;。在 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;webpack4&lt;/code&gt; 版本下相对 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;webpack3&lt;/code&gt;，做了很多优化，有了更好的默认值、更为简洁的模式设置、对 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;chunk&lt;/code&gt; 的分割也更加智能，&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;splitChunks&lt;/code&gt; 自定义如何分割代码块等等。对于整个项目来说，在包的构建速度、代码体积以及运行效率上都有一个质的飞跃。&lt;br /&gt;
webpack4默认的配置对于大部分简单应用来说已经够用了，但作为打包工具本身来说，它不可能满足所有的业务场景和形态，我们还是可以从中做一些优化来适配。&lt;br /&gt;
本文所述的优化均是基于 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;webpack4&lt;/code&gt; 而言。

&lt;h4 id=&quot;webpack内置分析工具&quot;&gt;webpack内置分析工具&lt;/h4&gt;
&lt;h5 id=&quot;1-stats&quot;&gt;1. &lt;strong&gt;stats&lt;/strong&gt;&lt;/h5&gt;
webpack构建完成后，用户可以生成一个包含模块统计信息 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;stats&lt;/code&gt; 的 JSON 文件。这个统计信息可以用来分析应用的依赖以便优化我们的构建。
生成方式如下：
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;webpack --profile --json &amp;gt; stats.json
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
输出的 JSON 文件内容如下：
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;{
  'version': '5.0.0-alpha.6', // Version of webpack used for the compilation
  'hash': '11593e3b3ac85436984a', // Compilation specific hash
  'time': 2469, // Compilation time in milliseconds
  'filteredModules': 0, // A count of excluded modules when exclude is passed to the toJson method
  'outputPath': ''/', // path to webpack output directory
  'assetsByChunkName': {
    // Chunk name to emitted asset(s) mapping
    'main': [
      'web.js?h=11593e3b3ac85436984a'
    ],
    'named-chunk': [
      'named-chunk.web.js'
    ],
    'other-chunk': [
      'other-chunk.js',
      'other-chunk.css'
    ]
  },
  'assets': [
    // A list of asset objects
  ],
  'chunks': [
    // A list of chunk objects
  ],
  'modules': [
    // A list of module objects
  ],
  'errors': [
    // A list of error strings
  ],
  'warnings': [
    // A list of warning strings
  ]
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
文件中包含了整个应用的构建信息，但是颗粒度不够细，对于分析意义不是很大。

&lt;h5 id=&quot;2-可视化构建分析&quot;&gt;2. 可视化构建分析&lt;/h5&gt;
体积分析工具 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;webpack-bundle-analyzer&lt;/code&gt;， 它可以将打包后的资源文件以方便交互的树状图来呈现，通过这个图我们可以直观的分析应用的模块组成，进一步分析然后优化它。

&lt;strong&gt;安装&lt;/strong&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;# npm
npm install -D webpack-bundle-analyzer

#yarn
yarn add -D webpack-bundle-analyzer
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;strong&gt;使用&lt;/strong&gt;
在 webpack.config.js 中配置

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
	plugins: [
	    new BundleAnalyzerPlugin()
	]
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
build 完成后，webpack-bundle-analyzer 会自动启动一个静态服务器并打开网页显示资源的树状图。如：
&lt;img src=&quot;./assets/tree.png&quot; alt=&quot;tree&quot; /&gt;

&lt;h5 id=&quot;3-report&quot;&gt;3. –report&lt;/h5&gt;
项目构建时加上 –report 可以自动打开浏览器，显示项目依赖界面。
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// package.json  
&quot;build&quot;: &quot;vue-cli-service build --report&quot;  
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;h3 id=&quot;webpack打包资源体积优化&quot;&gt;Webpack打包资源体积优化&lt;/h3&gt;
&lt;h4 id=&quot;1-打包拆分策略&quot;&gt;1. 打包拆分策略&lt;/h4&gt;
在做优化之前，我们必须对自己的项目工程结构有所了解，针对不同的业务场景，优化的侧重点也是不一样的。主要从以下几种类型几个维度来思考如何划分我们的包，并尽可能的利用浏览器缓存。&lt;br /&gt;
类型 | 共用频率 | 使用频率 | 更新频率 | 例如
&lt;ul&gt;
  &lt;li&gt;| :-: | :-: | :-: | -:
基础类库 | 高 | 高 | 低 | vue/react、vuex/mobx、x-router、axios等| 
UI组件库 | 高| 高 | 中 | iView、elment-ui、ant design等|&lt;br /&gt;
重要组件/函数 | 高| 高 | 中 | Menu/Header/Footer组件、路由钩子函数、权限拦截器、全局配置等|&lt;br /&gt;
业务代码 | 低| 高 | 高 | 业务组件、模块、页面等| 
低频组件 | 低| 低 | 低 | moment、d3、富文本等| &lt;br /&gt;
根据上表我们将代码划分为如下几类来进行拆分：&lt;/li&gt;
  &lt;li&gt;
    基础类库  libs&lt;br /&gt;
基础类库是项目中不可缺少的，如 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;vue&lt;/code&gt; + &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;vue-router&lt;/code&gt; + &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;vuex&lt;/code&gt; + &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;axios&lt;/code&gt; 这种标准的全家桶，升级频率不高，但每个页面都依赖他们，我们可以将它们单独提取出来进行打包。
  &lt;/li&gt;
  &lt;li&gt;
    UI 组件库&lt;br /&gt;
UI 组件库理论上也可以放入 libs 中，但是考虑到它一般比较大，比如 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;element-ui&lt;/code&gt; 压缩完接近 200kb 左右，而且 UI 组件库的更新频率也相对 libs 更高，我们会不时升级 UI 组件来解决 bug 或使用新功能，所以建议将UI 组件库单独拆包。
  &lt;/li&gt;
  &lt;li&gt;
    重要组件/函数&lt;br /&gt;
重要组件/函数在项目中必须加载他们才能正确运行，比如全局路由、菜单栏/header/footer等组件以及自定义的 SVG 图标等等，它们是入口必须的，默认打包到 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;app.js&lt;/code&gt; 中。&lt;br /&gt;
还有一些组件或函数没有在入口 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;entry&lt;/code&gt; 中引入，但是却被大部分页面使用，比如我们自己封装的 table 组件，由于体积不大，会被默认打包到每一个懒加载的页面 chunk 中去，假如有十个个页面引用了它，就会被重复打包十次，这样会造成不少的浪费。所以应该将那些复用频次高的公共组件单独打包。
  &lt;/li&gt;
  &lt;li&gt;业务代码&lt;br /&gt;
业务代码通常按照页面来打包，配合动态加载import()方法，将业务作为分离的模块起点，被请求的模块和它所引用的子模块，会分离到一个单独的chunk中。比如在 vue 中，使用 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;懒加载&lt;/code&gt; 的方式加载的页面
    &lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;component: () =&amp;gt; import('./Foo.vue')
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;    &lt;/div&gt;
    这样，webpack会将它打包成一个单独的 bundle 。
  &lt;/li&gt;
  &lt;li&gt;低频组件&lt;br /&gt;
低频组件和公共组件的区别在于，它们只会在特定的业务场景使用，比如富文本编辑器，这些库都是第三方并且体积大于 30kb， webpack4 会将它们默认打包成一个独立的 bundle。如果小于 30kb 会被打包到具体使用的页面 bundle 中。具体情况具体分析，通过 webpack 提供的 code spliting 完成。&lt;/li&gt;
&lt;/ul&gt;

完整的 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;splitCunks&lt;/code&gt; 配置如下：
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;splitChunks: {
  chunks: &quot;all&quot;,
  cacheGroups: {
    libs: {
      name: &quot;chunk-libs&quot;,
      test: /[\\/]node_modules[\\/]/,
      priority: 10,
      chunks: &quot;initial&quot; // 只打包初始时依赖的第三方
    },
    elementUI: {
      name: &quot;chunk-elementUI&quot;, // 单独将 elementUI 拆包
      priority: 20, // 权重要大于 libs 和 app 不然会被打包进 libs 或者 app
      test: /[\\/]node_modules[\\/]element-ui[\\/]/
    },
    commons: {
      name: &quot;chunk-comomns&quot;,
      test: resolve(&quot;src/components&quot;), // 可自定义拓展你的规则
      minChunks: 2, // 最小共用次数
      priority: 5,
      reuseExistingChunk: true
    }
  }
};
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

我们可以看看webpack4 提供了哪些默认的 optimization 配置，以便进一步结合自身项目来进行更改适配。
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// optimization 默认配置 

optimization: {
    minimize: env === 'production' ? true : false, // 开发环境不压缩
    splitChunks: {
        chunks: &quot;async&quot;, // 共有三个值可选：initial(初始模块)、async(按需加载模块)和all(全部模块)
        minSize: 30000, // 模块超过30k自动被抽离成公共模块
        minChunks: 1, // 模块被引用&amp;gt;=1次，便分割
        maxAsyncRequests: 5,  // 异步加载chunk的并发请求数量&amp;lt;=5
        maxInitialRequests: 3, // 一个入口并发加载的chunk数量&amp;lt;=3
        name: true, // 默认由模块名+hash命名，名称相同时多个模块将合并为1个，可以设置为function
        automaticNameDelimiter: '~', // 命名分隔符
        cacheGroups: { // 缓存组，将所有加载模块放在缓存里面一起分割打包
            default: { // 模块缓存规则，设置为false，默认缓存组将禁用
                minChunks: 2, // 模块被引用&amp;gt;=2次，拆分至vendors公共模块
                priority: -20, // 优先级
                reuseExistingChunk: true, // 默认使用已有的模块
            },
            vendors: {
                test: /[\\/]node_modules[\\/]/, // 表示默认拆分node_modules中的模块
                priority: -10
            }
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;h4 id=&quot;2-按需引入&quot;&gt;2. 按需引入&lt;/h4&gt;
我们在项目开发中经常会引用到一些第三方库，比如lodash，echarts，这些库在我们的项目中默认是全量引入的，但实际我们只用到库里的某些组件或者某些函数，按需打包我们使用的组件或函数就可以减少相当大一部分的体积。&lt;br /&gt;
以 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;lodash&lt;/code&gt; 为例，全包引入的话有 400kb 体积，使用模块化按需引入，可减少体积，具体做法是结合 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;lodash-webpack-plugin&lt;/code&gt; 和 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;babel-pluigin-lodash&lt;/code&gt;，它可将全路径引用的 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;lodash&lt;/code&gt; 自动转换为模块化引入，配置上也是十分简单。 ：

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// 引入组件，自动转换
import _ from 'lodash'
_.debounce()
_.throttle()

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
以上写法可能还是不够快捷，每个用到的文件都要写一遍 import，更可取的的方法是，将项目所需的方法，统一按需引入，组建一个本地的 lodash 库，然后导出 export 给我们的项目框架层，如 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Vue.prototype&lt;/code&gt;，以便我们全局使用。
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;import _ from 'lodash'
export default {
  cloneDeep: _.cloneDeep,
  debounce: _.debounce,
  throttle: _.throttle,
  size: _.size,
  pick: _.pick,
  isEmpty: _.isEmpty
}

// 注入到全局
import _ from '@helper/lodash.js'
Vue.prototype.$_ = _

// vue 组件内运用
this.$_.debounce()
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;3-压缩混淆&quot;&gt;3. 压缩混淆&lt;/h4&gt;
对于中等规模以上开发，我们一般区分 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;开发环境&lt;/code&gt;、&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;生产环境&lt;/code&gt;和&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;测试环境&lt;/code&gt;。对待生产环境，合理的压缩混淆可以有效的减小打包体积，同时移除一些调试信息，如 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;console&lt;/code&gt;。&lt;br /&gt;
webpack4 废弃了 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;CommonsChunkPlugin&lt;/code&gt;插件，使用 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;optimization.splitChunks&lt;/code&gt; 和 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;optimization.runtimeChunk&lt;/code&gt; 来替换。&lt;br /&gt;
webpack4 内置了 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;UglifyJs&lt;/code&gt; 插件，当打包模式 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;mode&lt;/code&gt; 为 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;production&lt;/code&gt; 时，会自动开启压缩js代码。&lt;br /&gt;
css压缩可以使用插件 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;optimize-css-assets-webpack-plugin&lt;/code&gt;。
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin')
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;optimization: {
    splitChunks: {
      chunks: 'all'
    },
    runtimeChunk: true,
    minimizer: [
      new OptimizeCssAssetsPlugin({})
    ]
  },
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;new OptimizeCssAssetsPlugin({
      assetNameRegExp: /\.optimize\.css$/g,
      cssProcessor: require('cssnano'),
      cssProcessorOptions: { safe: true, discardComments: { removeAll: true } },
      canPrint: true
    }),
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;h4 id=&quot;4-图片压缩&quot;&gt;4. 图片压缩&lt;/h4&gt;
webpack 打包时，会根据 webpack.config.js 中 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;url-loader&lt;/code&gt; 设置的 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;limit&lt;/code&gt; 大小对图片进行处理，小于 limit 的图片会转化成 base64 格式，其他的不做操作。对于较大的图片我们还可以用 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;image-webpack-loader&lt;/code&gt; 来压缩图片。
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// webpack.config.js 

{
  test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
  use:[
    {
    loader: 'url-loader',
    options: {
      limit: 10000,
      name: utils.assetsPath('img/[name].[hash:7].[ext]')
      }
    },
    {
      loader: 'image-webpack-loader',// 压缩图片
      options: {
        bypassOnDebug: true,
      }
    }
  ]
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;h4 id=&quot;5-开启gzip&quot;&gt;5. 开启Gzip&lt;/h4&gt;
关于 HTTP 压缩，百度百科的解释如下：
&lt;blockquote&gt;
  HTTP 压缩是一种内置到网页服务器和网页客户端中以改进传输速度和带宽利用率的方式。在使用 HTTP 压缩的情况下，HTTP 数据在从服务器发送前就已压缩：兼容的浏览器将在下载所需的格式前宣告支持何种方法给服务器；不支持压缩方法的浏览器将下载未经压缩的数据。最常见的压缩方案包括 Gzip 和 Deflate。
&lt;/blockquote&gt;

可以说，Gzip是 HTTP 压缩的经典。&lt;br /&gt;
&lt;strong&gt;Gzip 的好处&lt;/strong&gt;&lt;br /&gt;
开启Gzip可以减小文件体积，传输速度更快。服务端和客户端都可以做 Gzip。
&lt;ul&gt;
  &lt;li&gt;服务端可以使用 nginx 或 node 做压缩。&lt;/li&gt;
  &lt;li&gt;webpack可以通过插件做压缩。&lt;br /&gt;
webpack实现 Gzip:
    &lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;const CompressionWebpackPlugin = require('compression-webpack-plugin');
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;    &lt;/div&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;webpackConfig.plugins.push(
    new CompressionWebpackPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: new RegExp('\\.(js|css)$'),
      threshold: 10240,
      minRatio: 0.8
    })
)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
开启Gzip前 &lt;br /&gt;
&lt;img src=&quot;./assets/gzip前.jpg&quot; alt=&quot;gzip前&quot; /&gt;&lt;br /&gt;
开启 gzip 后 
&lt;img src=&quot;./assets/gzip后.jpg&quot; alt=&quot;gzip后&quot; /&gt;
webpack中的 Gzip主要是为了在构建过程中去做一部分服务器的工作，为服务器分压。服务器的 Gzip和 webpack 的 Gzip谁也不能替代谁，需要我们结合业务压力与服务器 CPU 情况来权衡。

&lt;h4 id=&quot;6-tree-shaking&quot;&gt;6. Tree-Shaking&lt;/h4&gt;
删除冗余代码的典型应用就是 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Tree-Shaking &lt;/code&gt;。&lt;br /&gt;
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Tree-Shaking &lt;/code&gt; 的消除原理是基于 ES6 的模块特性， 可以在编译过程中确定模块的依赖关系悉，获知哪些模块没有被真正使用，在打包的时候会将这些没用的代码删除掉。

举个例子：&lt;br /&gt;
在某个页面中
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;import { page1, page2 } from './pages'
    
// show是事先定义好的函数
show(page1)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
pages 文件里导出了两个页面：
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;export const page1 = xxx

export const page2 = xxx
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
但事实上，page2 并没有被用到，打包结果会把 ‘ export const page2 = xxx ‘这部分代码直接删掉。&lt;br /&gt;
注意：要使用 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Tree-Shaking &lt;/code&gt;，必须保证引用的模块都是 ES6 规范的,如果项目中使用了 Babel，这就比较麻烦了，因为 Babel的预置默认把模块转译成了 &lt;strong&gt;CommonJS&lt;/strong&gt; 模块，我们可以设置 modules: false 来解决此问题。(注：babel7 不推荐使用 babel-preset-2015， 而是 babel-preset-env 来实现基于特定环境引入需要的polyfill)&lt;br /&gt;
在 .babelrc 或者 webpack中设置。

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;/// .babelrc
{
  &quot;presets&quot;: [
    [&quot;env&quot;,
      {
        &quot;modules&quot;: false
      }
    ]
  ]
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// webpack.config.js
 
module: {
  rules: 
    {
      test: /\.js$/,
        exclude: /(node_modules)/,
          use: {
            loader: 'babel-loader',
            options: {
              presets: ['env', { modules: false }]
            }
          }
    }
  ]
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
为了在webpack中使 Tree-Shaking 起作用，需要满足许多条件，需要使用 &lt;strong&gt;ES6&lt;/strong&gt; 模块和 &lt;strong&gt;UglifyJsPlugin&lt;/strong&gt;，同时需要配置 &lt;strong&gt;optimization&lt;/strong&gt;，并将其 usedExports 和 sideEffects 设为 true。
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// webpack.config.js
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
 
module.exports = { 
  mode: 'none',
    optimization: {
      minimize: true,
      minimizer: [
        new UglifyJsPlugin()
      ],
      usedExports: true,
      sideEffects: true
    }
 
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

在当下，想要合理利用tree-shaking，能尽力做的事：

&lt;ul&gt;
  &lt;li&gt;使用 ES6 模块语法编写代码&lt;/li&gt;
  &lt;li&gt;尽量不写带有副作用的代码。诸如编写了立即执行函数，在函数里又使用了外部变量等&lt;/li&gt;
  &lt;li&gt;工具类函数尽量以单独的形式输出，不要集中成一个对象或者类&lt;/li&gt;
  &lt;li&gt;声明 sideEffects&lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;7-公共文件提取&quot;&gt;7. 公共文件提取&lt;/h4&gt;
虽然我们对代码进行了拆分优化，但是在编译过程中，每次都需要对这些基础组件进行打包，对于不常更新的第三方库我们可以提前进行打包，在持续构建的过程中，就可以节省这部分时间了。  &lt;br /&gt;
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;DllPlugin&lt;/code&gt; 就是这样一个提前打包的插件，在 webpack 中通过 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;DllReferencePlugin&lt;/code&gt; 引入提前打包好的文件，最后使用 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;AddAssetHtmlPlugin&lt;/code&gt;  往里注入 vendor 文件。&lt;br /&gt;
webpack.dll.conf.js 配置如下：

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// webpack.dll.conf.js
const webpack = require('webpack');
const path = require('path');
const dllDist = path.join(__dirname, 'dist');

module.exports = {
  entry: {
    vendor: ['vue', 'vuex', 'vue-router', 'axios', 'moment'],
  },

  output: {
    path: const dllDist = path.join(__dirname, 'dist'),
    filename: '[name]-[hash].js',
    library: '[name]',
  },
  optimization: {
    minimizer: [
    ],
  },
  plugins: [
    new CleanWebpackPlugin([&quot;*.js&quot;], { // 清除之前的dll文件
      root: dllDist,
    }),
    new webpack.DllPlugin({
      path: path.join(__dirname, 'dll', '[name]-manifest.json'),
      name: '[name]',
    }),
  ]
};
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
webpack配置
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;const manifest = require('./dll/vendor-manifest.json');
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin');
...
plugins: [
    // webpack读取到vendor的manifest文件对于vendor的依赖不会进行编译打包
    new webpack.DllReferencePlugin({
      manifest,
    }),
    // 往html中注入vendor js
    new AddAssetHtmlPlugin([{ 
      publicPath: &quot;/view/static/js&quot;,  // 注入到html中的路径
      outputPath: &quot;../build/static/js&quot;, // 最终输出的目录
      filepath: path.resolve(__dirname, './dist/*.js'),
      includeSourcemap: false,
      typeOfAsset: &quot;js&quot;
    }]),
]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
注意：当组件库更新时需要手动升级，并执行 dll 命令，更新我们的 vendor 文件。

&lt;h4 id=&quot;其他建议&quot;&gt;其他建议&lt;/h4&gt;
&lt;strong&gt;包引入的必要性&lt;/strong&gt; &lt;br /&gt;
现在的前端大多是 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MVVM&lt;/code&gt; 模式的框架，基于数据的双向绑定，像 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;jQuery&lt;/code&gt; 这样的库，完全没有引入的必要，用几行原生代码能解决的事，没有必要引入这样的庞然大物。

&lt;strong&gt;避免引而不用&lt;/strong&gt;&lt;br /&gt;
在大型项目中，很难保证每个引入的库都被利用到，如果有引入却未使用的类库，只会徒增打包体积，影响性能。这时可以借助工具在开发时进行约束，推荐使用 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ESlint&lt;/code&gt; 等这类工具，注入规则，对声明未使用的代码进行强制提醒，有效避免类似情况发生，还能统一团队开发规范，一举多得。

&lt;strong&gt;引入适合的包&lt;/strong&gt;&lt;br /&gt;
类似 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;momentjs&lt;/code&gt;，它给我们带来便利的同时，也在一定程度上影响了性能，和它功能类似的类库还有很多，我们可以选择体积更加小的，满足开发需求即可。

&lt;h3 id=&quot;代码分割--optimizationsplitchunks&quot;&gt;代码分割 &amp;amp; &lt;strong&gt;optimization.splitChunks&lt;/strong&gt;&lt;/h3&gt;

&lt;h4 id=&quot;代码分割的本质&quot;&gt;代码分割的本质&lt;/h4&gt;
&lt;img src=&quot;./assets/code-splitting.png&quot; alt=&quot;代码分割本质&quot; /&gt;

&lt;blockquote&gt;
  代码分割的本质就是在&lt;strong&gt;源代码直接上线&lt;/strong&gt;和&lt;strong&gt;打包成唯一的脚本main.bundle.js&lt;/strong&gt;这两种极端方案之间寻找一个更适合实际业务场景的中间状态，用可接受的服务器性能压力增加来换取更好的用户体验。
&lt;/blockquote&gt;

&lt;strong&gt;splitChunks基本配置&lt;/strong&gt;

1、&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;chunks&lt;/code&gt; 分割代码的模式

&lt;ul&gt;
  &lt;li&gt;all: 不管文件是动态还是非动态引入，统一将文件进行分离。当页面首次载入时会引入所有的包。&lt;/li&gt;
  &lt;li&gt;async: 将异步加载文件进行分离，首次一般不引入，到需要异步引入的组件才会引入。&lt;/li&gt;
  &lt;li&gt;initial: 只分割同步引入的模块,及入口模块。&lt;/li&gt;
&lt;/ul&gt;

2、&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;minSize&lt;/code&gt; 表示抽取出来的文件在压缩前的最小大小，单位为 byte，默认为30000。

3、 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;maxSize&lt;/code&gt; 表示抽取出来的文件在压缩前的最大大小，默认为 0，表示不限制最大大小。

4、 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;minChunks&lt;/code&gt; 模块最小引用次数&lt;br /&gt;
如当值为2时，表示只引用了一次的模块不做分割打包处理。

5、 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;maxAsyncRequests&lt;/code&gt; 按需(异步)加载模块最大并行请求数，默认为5 
如：打开某个页面需要同时加载10个库，且设置 maxAsyncRequests: 5，那么这10个库会被分割成5个模块。

6、&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;maxInitialRequests&lt;/code&gt; 入口文件可并行加载的最大文件数量，默认为3 
如：maxInitialRequests: 3，有pageA中，使用了大量 import xx from ‘yy’，那么pageA依赖的这些非动态加载的模块，最多只会被打包成3个模块。

7、&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;automaticNameDelimiter&lt;/code&gt; 缓存组名称和生成文件名称之间的连接字符串

&lt;ul&gt;
  &lt;li&gt;name 为 true 时，分割文件名为 [缓存组名][连接符][入口文件名].js&lt;/li&gt;
  &lt;li&gt;name 为 false 时，分割文件名为 [模块id][连接符][入口文件名].js&lt;/li&gt;
  &lt;li&gt;如果缓存组存在 name 属性，则以缓存组的 name 属性为准&lt;/li&gt;
&lt;/ul&gt;

8、&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;cacheGroups&lt;/code&gt; 缓存组，splitChunks最核心的配置，上面的属性都是对缓存组进行配置的，且缓存组会继承splitChunks的配置。&lt;br /&gt;
当符合代码分割的条件时，就会进入缓存组，把各个模块进行分组，最后一块分割打包。&lt;br /&gt;
splitChunks默认有两个缓存组: vendors 和 default：
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;optimization: {
    splitChunks: {
      ...
      cacheGroups: {
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          priority: -10
        },
        default: {
          minChunks: 2,
          priority: -20,
          reuseExistingChunk: true
        }
      }
    }
  }
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h3 id=&quot;prefetch--preload&quot;&gt;prefetch &amp;amp; preload&lt;/h3&gt;
&lt;strong&gt;引入&lt;/strong&gt;&lt;br /&gt;
异步加载模块解决了首页加载慢的问题，但同时可能因为异步加载的那部分代码迟迟不能执行，导致用户交互长时间没有响应，影响用户体验。&lt;br /&gt;
这时候就需要 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;prefetch&lt;/code&gt; 和 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;preload&lt;/code&gt; 了。&lt;br /&gt;
&lt;strong&gt;Webpack 4.6.0&lt;/strong&gt; 为我们提供了&lt;strong&gt;预先拉取（prefetch）&lt;/strong&gt; 和 &lt;strong&gt;预先加载（preloading）&lt;/strong&gt; 功能，使用这些声明可以修改浏览器处理异步chunk的方式。

&lt;strong&gt;预先拉取&lt;/strong&gt;&lt;br /&gt;
表示该模块可能以后会用到，浏览器会在空闲时间下载该模块，且下载是发生在父级chunk加载完成之后。
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;import(
  `./module/a`
  /* webpackPrefetch: true */
  /* webpackChunkName: 'a'*/
)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
这样的导入会在页面头部添加一段如下代码：
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;lt;link rel=&quot;prefetch&quot; as=&quot;script&quot; href=&quot;a.js&quot; &amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
因此浏览器会在空闲时间预先拉取该文件。

&lt;strong&gt;预先加载&lt;/strong&gt;&lt;br /&gt;
对资源添加预先加载的注释，指明该模块需要立即被使用，异步chunk和父级chunk并行加载。如果父级chunk先下载好，页面即可显示，同时等待异步chunk的下载。这能大幅提升性能。
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;import(
  `./module/a`
  /* webpackPreload: true */
  /* webpackChunkName: 'a' */
)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
以上代码会在页面头部添加如下代码：
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&amp;lt;link rel=&quot;preload&quot; as=&quot;script&quot; href=&quot;a.js&quot; &amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;strong&gt;小结&lt;/strong&gt;&lt;br /&gt;
 使用&lt;strong&gt;动态导入&lt;/strong&gt;能提升应用性能，显著减少页面的初次加载时间。同时配合webpack的额外参数，添加预先拉取和预先加载的支持，可以进一步定制动态导入，优化用户体验。

&lt;h3 id=&quot;典型案例&quot;&gt;典型案例&lt;/h3&gt;
&lt;h4 id=&quot;1首屏加载优化&quot;&gt;1、首屏加载优化&lt;/h4&gt;
先看图&lt;br /&gt;
&lt;img src=&quot;./assets/home.png&quot; alt=&quot;home&quot; /&gt;&lt;br /&gt;
router:&lt;br /&gt;
&lt;img src=&quot;./assets/router.png&quot; alt=&quot;router&quot; /&gt;&lt;br /&gt;
以上是使用懒加载的方式加载的路由&lt;br /&gt;
打包结果:&lt;br /&gt;
&lt;img src=&quot;./assets/build.png&quot; alt=&quot;build&quot; /&gt;

看看首页加载的资源&lt;br /&gt;
&lt;img src=&quot;./assets/app.png&quot; alt=&quot;home&quot; /&gt;

结果显示，首页还是将所有资源加载了。&lt;br /&gt;
看看首页head

&lt;img src=&quot;./assets/head.png&quot; alt=&quot;head&quot; /&gt;&lt;br /&gt;
发现 &lt;em&gt;about.js&lt;/em&gt; &lt;em&gt;list.js&lt;/em&gt;  被加上了 &lt;strong&gt;prefetch&lt;/strong&gt;，被预先拉取了。某些情况下我们可能不想这么做，查看 vue-cli 官方文档发现：

&lt;blockquote&gt;
  默认情况下，一个 Vue CLI 应用会为所有作为 async chunk 生成的 JavaScript 文件 (通过动态 import() &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;按需 code splitting&lt;/code&gt; 的产物) 自动生成 prefetch 提示。
&lt;/blockquote&gt;

&lt;blockquote&gt;
  这些提示会被 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;@vue/preload-webpack-plugin&lt;/code&gt; 注入，并且可以通过 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;chainWebpack&lt;/code&gt; 的 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;config.plugin('prefetch')&lt;/code&gt; 进行修改和删除。
&lt;/blockquote&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;// vue.config.js
module.exports = {
  chainWebpack: config =&amp;gt; {
    // 移除 prefetch 插件
    config.plugins.delete('prefetch')

    // 或者
    // 修改它的选项：
    config.plugin('prefetch').tap(options =&amp;gt; {
      options[0].fileBlacklist = options[0].fileBlacklist || []
      options[0].fileBlacklist.push(/myasyncRoute(.)+?\.js$/)
      return options
    })
  }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

再来看看首页：&lt;br /&gt;
&lt;img src=&quot;./assets/home2.png&quot; alt=&quot;home2&quot; /&gt;&lt;br /&gt;
点击 About，加载了About.js&lt;br /&gt;
&lt;img src=&quot;./assets/about.png&quot; alt=&quot;about&quot; /&gt;

这样完成了对首页加载资源的优化。

如果我们需要设置资源预先拉取/加载，则可以通过webpack魔法注释 &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;/* webpackPrefetch: true */&lt;/code&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;/* webpackPreload: true */&lt;/code&gt; 来手动设置。

</description>
        <pubDate>Thu, 02 Apr 2020 00:00:00 +0000</pubDate>
        <link>https://heiguagua.github.io/2020/04/02/webpack%E9%9D%99%E6%80%81%E8%B5%84%E6%BA%90%E4%BD%93%E7%A7%AF%E5%88%86%E6%9E%90%E4%B8%8E%E6%80%BB%E7%BB%93/</link>
        <guid isPermaLink="true">https://heiguagua.github.io/2020/04/02/webpack%E9%9D%99%E6%80%81%E8%B5%84%E6%BA%90%E4%BD%93%E7%A7%AF%E5%88%86%E6%9E%90%E4%B8%8E%E6%80%BB%E7%BB%93/</guid>
        
        <category>webpack4</category>
        
        <category>optimization</category>
        
        <category>Gzip</category>
        
        <category>prefetch</category>
        
        <category>preload</category>
        
        <category>按需加载</category>
        
        
        <category>Web</category>
        
      </item>
    
      <item>
        <title>Vue采坑记</title>
        <description>
</description>
        <pubDate>Thu, 02 Apr 2020 00:00:00 +0000</pubDate>
        <link>https://heiguagua.github.io/2020/04/02/vue%E9%87%87%E5%9D%91%E8%AE%B0/</link>
        <guid isPermaLink="true">https://heiguagua.github.io/2020/04/02/vue%E9%87%87%E5%9D%91%E8%AE%B0/</guid>
        
        
      </item>
    
      <item>
        <title>大屏开发经验总结</title>
        <description>&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#大屏开发经验总结&quot; id=&quot;markdown-toc-大屏开发经验总结&quot;&gt;&lt;strong&gt;大屏开发经验总结&lt;/strong&gt;&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#框架及设计&quot; id=&quot;markdown-toc-框架及设计&quot;&gt;&lt;strong&gt;框架及设计&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#图表库的选择&quot; id=&quot;markdown-toc-图表库的选择&quot;&gt;&lt;strong&gt;图表库的选择&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#页面布局&quot; id=&quot;markdown-toc-页面布局&quot;&gt;&lt;strong&gt;页面布局&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#自适应网页的实现&quot; id=&quot;markdown-toc-自适应网页的实现&quot;&gt;&lt;strong&gt;自适应网页的实现&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#性能优化&quot; id=&quot;markdown-toc-性能优化&quot;&gt;&lt;strong&gt;性能优化&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;大屏开发经验总结&quot;&gt;&lt;strong&gt;大屏开发经验总结&lt;/strong&gt;&lt;/h3&gt;
&lt;hr /&gt;

&lt;h5 id=&quot;框架及设计&quot;&gt;&lt;strong&gt;框架及设计&lt;/strong&gt;&lt;/h5&gt;

其实可视化的web开发和传统网页开发并没有什么本质区别。都是数据+模板。前后端分离什么的，跟传统网页开发也没山么区别。现在流行的是用node作为中间层，数据处理交给java或者其他。（对于体量小的应用，不需要设计这么复杂）

首先根据项目及人员配备情况，选择合适的前端框架，个人觉得用vue效率比较高且跟得上现在的技术。以及确定是否需要使用前后端分离。

在UI设计过程中，最好能及时沟通一些技术细节，避免设计出的效果现有技术不能达到要求或者具有太大的技术难度。最终商量确定折中方案实施。

&lt;h5 id=&quot;图表库的选择&quot;&gt;&lt;strong&gt;图表库的选择&lt;/strong&gt;&lt;/h5&gt;

可视化的关键就是能直观生动的将数据进行展示，对页面的动效要求和图表统计分析比传统网页要多，选择合适的插件非常重要。常用的echarts或highcharts，d3.js，如果要求3d效果，可以采用wegGL技术。

&lt;strong&gt;echarts&lt;/strong&gt;&lt;br /&gt;
echarts是百度开源的，底层是canvas。支持很多丰富的图表，官网实例也非常多，兼容性不考虑IE低版本的话是非常不错的选择。4.0版本据说支持千万级别数据量渲染，同时增加了svg引擎包裹。

&lt;strong&gt;highcharts&lt;/strong&gt;&lt;br /&gt;
highcharts底层是svg的，商业使用需要授权。在浏览器兼容性支持上比echarts好，但是实例较少，个人更偏向使用echarts。

&lt;strong&gt;canvas vs svg&lt;/strong&gt;
&lt;ul&gt;
  &lt;li&gt;canvas依赖于分辨率，而svg不依赖，也就是说浏览器缩放时canvas会变形而svg不会。&lt;/li&gt;
  &lt;li&gt;canvas不支持事件处理，svg支持事件处理。&lt;/li&gt;
  &lt;li&gt;对于移动端，canvas不太友好，而svg内存占用小&lt;/li&gt;
  &lt;li&gt;数据量大交互多时，canvas占优势，svg渲染性能较差。&lt;/li&gt;
&lt;/ul&gt;

&lt;h5 id=&quot;页面布局&quot;&gt;&lt;strong&gt;页面布局&lt;/strong&gt;&lt;/h5&gt;

在开始着手设计页面时，首先得考虑页面以怎样的方式布局，他是一个静态网页，还是一个自适应或者响应式？

&lt;strong&gt;静态网页&lt;/strong&gt;&lt;br /&gt;
所谓静态网页就是采用固定的宽度实现的页面。

&lt;strong&gt;自适应&lt;/strong&gt;&lt;br /&gt;
自适应是为了解决如何才能在不同大小的设备上呈现同样的网页。

&lt;strong&gt;响应式&lt;/strong&gt;&lt;br /&gt;
响应式可以自动识别屏幕宽度，并作出响应调整，布局和展示的内容在不同屏幕下可能不同。众所周知，twitter开源的bootstrap就是一套响应式的UI框架。

在做可视化大屏展示时，根据需求选择使用哪一种网页布局。一般采用静态或者自适应。

&lt;h5 id=&quot;自适应网页的实现&quot;&gt;&lt;strong&gt;自适应网页的实现&lt;/strong&gt;&lt;/h5&gt;
&lt;ol&gt;
  &lt;li&gt;允许网页宽度自动调整&lt;br /&gt;
在网页代码的头部，加上viewport meta
    &lt;div class=&quot;language-html highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; &lt;span class=&quot;nt&quot;&gt;&amp;lt;meta&lt;/span&gt; &lt;span class=&quot;na&quot;&gt;name=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;viewport&quot;&lt;/span&gt; &lt;span class=&quot;na&quot;&gt;content=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;width=device-width, initial-scale=1&quot;&lt;/span&gt; &lt;span class=&quot;nt&quot;&gt;/&amp;gt;&lt;/span&gt;  
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;    &lt;/div&gt;
  &lt;/li&gt;
  &lt;li&gt;尽量避免使用绝对宽度&lt;br /&gt;
由于网页会根据屏幕宽度调整布局，所以不能使用绝对宽度的布局，通过指定百分比来替代。&lt;/li&gt;
  &lt;li&gt;相对大小的字体&lt;br /&gt;
字体同样不能使用绝对大小(px)，而使用相对大小（em）或高清方案（rem），上面的宽度也可以使用。&lt;/li&gt;
  &lt;li&gt;选择性加载css&lt;br /&gt;
自适应网页设计的核心就是css3引入的&lt;strong&gt;Media Query&lt;/strong&gt;。&lt;br /&gt;
例子：
    &lt;div class=&quot;language-html highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; &lt;span class=&quot;nt&quot;&gt;&amp;lt;link&lt;/span&gt; &lt;span class=&quot;na&quot;&gt;rel=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;stylesheet&quot;&lt;/span&gt; &lt;span class=&quot;na&quot;&gt;type=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;text/css&quot;&lt;/span&gt;  &lt;span class=&quot;na&quot;&gt;media=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;screen and (max-device-width: 400px)&quot;&lt;/span&gt;  &lt;span class=&quot;na&quot;&gt;href=&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;tinyScreen.css&quot;&lt;/span&gt; &lt;span class=&quot;nt&quot;&gt;/&amp;gt;&lt;/span&gt;  
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;    &lt;/div&gt;
  &lt;/li&gt;
  &lt;li&gt;css的@media规则&lt;br /&gt;
同一个css文件中，可以根据不同的屏幕分辨率，选择性的应用不同的css规则。
    &lt;div class=&quot;language-css highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; &lt;span class=&quot;k&quot;&gt;@media&lt;/span&gt;  &lt;span class=&quot;n&quot;&gt;screen&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;and&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;max-device-width&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;m&quot;&gt;400px&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;  
    
 &lt;span class=&quot;err&quot;&gt;　　　　&lt;/span&gt;&lt;span class=&quot;nc&quot;&gt;.column&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;  
 &lt;span class=&quot;err&quot;&gt;　　　　　　&lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;float&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;none&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;  
 &lt;span class=&quot;err&quot;&gt;　　　　　　&lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;width&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;auto&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;  
 &lt;span class=&quot;err&quot;&gt;　　　　&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;  
    
 &lt;span class=&quot;err&quot;&gt;　　　　&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;#sidebar&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;  
 &lt;span class=&quot;err&quot;&gt;　　　　　　&lt;/span&gt;&lt;span class=&quot;nl&quot;&gt;display&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;none&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;  
 &lt;span class=&quot;err&quot;&gt;　　　　&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;  
    
 &lt;span class=&quot;err&quot;&gt;　　&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;  
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;    &lt;/div&gt;
  &lt;/li&gt;
  &lt;li&gt;图片的自适应&lt;br /&gt;
除了页面布局和文本需要自适应外，图片也必须实现&lt;strong&gt;自动缩放&lt;/strong&gt;。通过css来实现：
    &lt;div class=&quot;language-css highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; &lt;span class=&quot;nt&quot;&gt;img&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;nl&quot;&gt;max-width&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;m&quot;&gt;100%&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;}&lt;/span&gt;  
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;    &lt;/div&gt;

    老版本的IE不支持max-width，可以使用：
    &lt;div class=&quot;language-css highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt; &lt;span class=&quot;nt&quot;&gt;img&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;nl&quot;&gt;width&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;m&quot;&gt;100%&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;    &lt;/div&gt;
  &lt;/li&gt;
  &lt;li&gt;flexbox布局&lt;br /&gt;
flexbox布局就是我们经常说的弹性布局。它是css3新增的一种布局模式，可以很方便地用来改善动态或者未知大小的元素的对齐和方向等。&lt;/li&gt;
&lt;/ol&gt;

flex容器的主要特性是她可以调整其子元素的宽度或者高度来填充可用的空白区域，以最优的方式达到兼容大小。使用felx布局需要写一些浏览器的hack，IE低版本（10-）不支持flex布局。

&lt;h5 id=&quot;性能优化&quot;&gt;&lt;strong&gt;性能优化&lt;/strong&gt;&lt;/h5&gt;
有时我们访问一个网页，会感觉很卡顿，一方面除了网络带宽原因外，页面的渲染性能也有很大的影响。

首先，我们得了解浏览器渲染的过程，浏览器从解析一个页面到渲染做了哪些事呢？

&lt;ol&gt;
  &lt;li&gt;&lt;strong&gt;转化：&lt;/strong&gt; 浏览器从磁盘或网络读取HTML的原始字节，并按照相应编码规范（一般为utf-8）进行编码。&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;符号化：&lt;/strong&gt; 根据W3C标准转换为对应的标签符号。&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;DOM构建：&lt;/strong&gt; HTML解析器解析其中的标签，生成token，遇到css或js会发送相应的请求。根据token生成相应的DOM树。&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;CSSOM构建：&lt;/strong&gt; 添加CSS样式生成CSSOM树。&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;渲染树构建：&lt;/strong&gt; 从DOM树的根节点开始，遍历每个可见的节点，给每个节点找到相应匹配的CSSOM规则，应用这些规则，连带其内容及计算的样式。&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;样式计算：&lt;/strong&gt; 浏览器会将所有的相对位置转换成绝对位置等一系列的样式计算。&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;布局：&lt;/strong&gt; 浏览器将元素进行定位和布局。&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;绘制：&lt;/strong&gt; 绘制元素样式，颜色、背景、大小、边框等等。&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;合成：&lt;/strong&gt; 将各个层合成到一起，显示在屏幕上。&lt;/li&gt;
&lt;/ol&gt;

在理解渲染性能之前，我们有必要了解一下两个概念，那就是&lt;strong&gt;重排（&lt;em&gt;也叫回流，Reflow&lt;/em&gt;）&lt;/strong&gt;和&lt;strong&gt;重绘（&lt;em&gt;repaint&lt;/em&gt;）&lt;/strong&gt;。

&lt;strong&gt;重排（&lt;em&gt;Reflow&lt;/em&gt;）&lt;/strong&gt;&lt;br /&gt;
重排指的是计算页面布局，包括节点的尺寸和位置，还有可能触发其子节点的Reflow。

当渲染树中的一部分或全部因为元素的尺寸、布局、隐藏等改变而需要重新构建，这就叫回流，每个页面至少需要一次回流，就是页面第一次加载的时候。

在web网页中，很多状况会导致回流：
&lt;ul&gt;
  &lt;li&gt;调整窗口大小&lt;/li&gt;
  &lt;li&gt;改变字体&lt;/li&gt;
  &lt;li&gt;增加或移除样式元素&lt;/li&gt;
  &lt;li&gt;内容变化&lt;/li&gt;
  &lt;li&gt;激活css伪类&lt;/li&gt;
  &lt;li&gt;操作css属性&lt;/li&gt;
  &lt;li&gt;操作DOM&lt;/li&gt;
  &lt;li&gt;css3 Animation或transition&lt;/li&gt;
&lt;/ul&gt;

&lt;strong&gt;重绘（&lt;em&gt;Repaint&lt;/em&gt;）&lt;/strong&gt;&lt;br /&gt;
当渲染树中的一些元素需要更新属性，而这些属性只是影响元素的外观、风格、而不会影响布局的，就是重绘。

回流和重绘都很容易被触发，他们的触发对性能的影响都非常大，我们无法完全避免，只能尽量不触发。

&lt;ol&gt;
  &lt;li&gt;
    避免触发布局&lt;br /&gt;
目前，transform和opacity只会引起合成图层，不会引起布局和重绘。性能是最好的。所以在制作动画时，建议使用&lt;strong&gt;transform的&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;translate&lt;/code&gt;&lt;/strong&gt;替代&lt;strong&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;margin&lt;/code&gt;&lt;/strong&gt;或&lt;strong&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;position&lt;/code&gt;&lt;/strong&gt;中的&lt;strong&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;top&lt;/code&gt;&lt;/strong&gt;、&lt;strong&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;right&lt;/code&gt;&lt;/strong&gt;、&lt;strong&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;bottom&lt;/code&gt;&lt;/strong&gt;、&lt;strong&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;left&lt;/code&gt;&lt;/strong&gt;，同时使用&lt;strong&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;transform&lt;/code&gt;&lt;/strong&gt;中的&lt;strong&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scaleX&lt;/code&gt;&lt;/strong&gt;或&lt;strong&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;scaleY&lt;/code&gt;&lt;/strong&gt;替代&lt;strong&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;width&lt;/code&gt;&lt;/strong&gt;和&lt;strong&gt;&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;height&lt;/code&gt;&lt;/strong&gt;
  &lt;/li&gt;
  &lt;li&gt;避免长时间渲染
    &lt;ul&gt;
      &lt;li&gt;复杂的css，如过多的属性嵌套或者复杂的样式计算&lt;/li&gt;
      &lt;li&gt;Image Decodes，图片解码及图片大小的设置&lt;/li&gt;
      &lt;li&gt;大的空图层&lt;br /&gt;
以上这些都花费长时间来渲染，应避免。&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;使用css提供的新特性&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;will-change&lt;/code&gt;&lt;br /&gt;
&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;will-change&lt;/code&gt;的主要作用就是&lt;strong&gt;提前告知浏览器将会进行的一些变动，告诉浏览器分配资源&lt;/strong&gt;。&lt;/li&gt;
&lt;/ol&gt;

但是注意，不要将&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;will-change&lt;/code&gt;应用到太多元素上，也不要过早的应用&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;will-change&lt;/code&gt;，并注意在应用变化之后，取消&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;will-change&lt;/code&gt;的资源分配。

</description>
        <pubDate>Thu, 17 May 2018 00:00:00 +0000</pubDate>
        <link>https://heiguagua.github.io/2018/05/17/%E5%A4%A7%E5%B1%8F%E5%BC%80%E5%8F%91%E7%BB%8F%E9%AA%8C%E6%80%BB%E7%BB%93/</link>
        <guid isPermaLink="true">https://heiguagua.github.io/2018/05/17/%E5%A4%A7%E5%B1%8F%E5%BC%80%E5%8F%91%E7%BB%8F%E9%AA%8C%E6%80%BB%E7%BB%93/</guid>
        
        <category>大屏</category>
        
        <category>可视化</category>
        
        
        <category>Web</category>
        
      </item>
    
      <item>
        <title>js异步事件处理</title>
        <description>&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#js中的异步事件处理&quot; id=&quot;markdown-toc-js中的异步事件处理&quot;&gt;&lt;strong&gt;js中的异步事件处理&lt;/strong&gt;&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#11-什么是promise&quot; id=&quot;markdown-toc-11-什么是promise&quot;&gt;&lt;strong&gt;1.1 什么是Promise&lt;/strong&gt;&lt;/a&gt;        &lt;ul&gt;
          &lt;li&gt;&lt;a href=&quot;#111-promise的语法&quot; id=&quot;markdown-toc-111-promise的语法&quot;&gt;&lt;strong&gt;1.1.1 Promise的语法&lt;/strong&gt;&lt;/a&gt;            &lt;ul&gt;
              &lt;li&gt;&lt;a href=&quot;#constructor&quot; id=&quot;markdown-toc-constructor&quot;&gt;&lt;strong&gt;Constructor&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
              &lt;li&gt;&lt;a href=&quot;#instance-method&quot; id=&quot;markdown-toc-instance-method&quot;&gt;&lt;strong&gt;Instance Method&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
              &lt;li&gt;&lt;a href=&quot;#static-method&quot; id=&quot;markdown-toc-static-method&quot;&gt;&lt;strong&gt;Static Method&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
            &lt;/ul&gt;
          &lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#112-promise的三种状态&quot; id=&quot;markdown-toc-112-promise的三种状态&quot;&gt;&lt;strong&gt;1.1.2 Promise的三种状态&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#113-promise示例代码&quot; id=&quot;markdown-toc-113-promise示例代码&quot;&gt;&lt;strong&gt;1.1.3 Promise示例代码&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#12-promiseprototype&quot; id=&quot;markdown-toc-12-promiseprototype&quot;&gt;&lt;strong&gt;1.2 Promise.prototype&lt;/strong&gt;&lt;/a&gt;        &lt;ul&gt;
          &lt;li&gt;&lt;a href=&quot;#promiseprototypeconstructor&quot; id=&quot;markdown-toc-promiseprototypeconstructor&quot;&gt;&lt;strong&gt;Promise.prototype.constructor&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#promiseprototypethenonfulfilled-onrejected&quot; id=&quot;markdown-toc-promiseprototypethenonfulfilled-onrejected&quot;&gt;&lt;strong&gt;Promise.prototype.then(onFulfilled, onRejected)&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#promiseprototypecatchonrejected&quot; id=&quot;markdown-toc-promiseprototypecatchonrejected&quot;&gt;&lt;strong&gt;Promise.prototype.catch(onRejected)&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#promiseprototypefinallyonfinally&quot; id=&quot;markdown-toc-promiseprototypefinallyonfinally&quot;&gt;&lt;strong&gt;Promise.prototype.finally(onFinally)&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#promise的静态方法&quot; id=&quot;markdown-toc-promise的静态方法&quot;&gt;&lt;strong&gt;Promise的静态方法&lt;/strong&gt;&lt;/a&gt;        &lt;ul&gt;
          &lt;li&gt;&lt;a href=&quot;#promiseresolve&quot; id=&quot;markdown-toc-promiseresolve&quot;&gt;&lt;strong&gt;Promise.resolve&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#promisealliterable&quot; id=&quot;markdown-toc-promisealliterable&quot;&gt;&lt;strong&gt;Promise.all(iterable)&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
          &lt;li&gt;&lt;a href=&quot;#promiseraceiterable&quot; id=&quot;markdown-toc-promiseraceiterable&quot;&gt;&lt;strong&gt;Promise.race(iterable)&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
        &lt;/ul&gt;
      &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;js中的异步事件处理&quot;&gt;&lt;strong&gt;js中的异步事件处理&lt;/strong&gt;&lt;/h3&gt;
&lt;hr /&gt;

ES6诞生以前，异步编程的方法主要有以下几种：&lt;strong&gt;回调函数、事件监听、发布/订阅、Promise对象&lt;/strong&gt;；ES6中引入了&lt;strong&gt;Generator函数&lt;/strong&gt;；ES7中，&lt;strong&gt;async/await&lt;/strong&gt;将异步编程带入了一个全新的阶段。

文章将对这些异步操作的使用和优缺点进行进一步的比较和分析。本文内容部分摘抄自&lt;a href=&quot;https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise&quot;&gt;《Mozilla Promise Reference》&lt;/a&gt;。

&lt;h4 id=&quot;11-什么是promise&quot;&gt;&lt;strong&gt;1.1 什么是Promise&lt;/strong&gt;&lt;/h4&gt;

Promise是抽象异步处理对象以及对其进行各种操作的组件。

&lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;// 使用了回调函数的异步处理&lt;/span&gt;
&lt;span class=&quot;nx&quot;&gt;getAsync&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;fileA.txt&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;function&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;result&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 取得失败时的处理&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;throw&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// 成功时的处理&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

Node.js规定在javascript的回调函数中的第一个参数为&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Error&lt;/code&gt;对象。

下面看个使用了Promise进行异步处理的例子：

&lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;promise&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;getAsyncPromise&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;fileA.txt&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 返回Promise对象&lt;/span&gt;
&lt;span class=&quot;nx&quot;&gt;promise&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;then&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kd&quot;&gt;function&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;result&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// 成功时的处理&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}).&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;catch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kd&quot;&gt;function&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// 失败时的处理&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

两者比较，回调函数方式可以自己定义回调函数的采纳数，而使用promise对象处理的时候，除了promise规定的&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;then&lt;/code&gt;和&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;catch&lt;/code&gt;以外的方法都是不可以使用的，必须严格遵守固定、统一的编程方式来写代码。

所以，promise的功能就是可以将复杂的异步处理轻松的进行模式化。

&lt;h5 id=&quot;111-promise的语法&quot;&gt;&lt;strong&gt;1.1.1 Promise的语法&lt;/strong&gt;&lt;/h5&gt;

Promise的使用大概有以下三种类型：

&lt;h6 id=&quot;constructor&quot;&gt;&lt;strong&gt;Constructor&lt;/strong&gt;&lt;/h6&gt;

Promise类似于&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;XMLHttpRequest&lt;/code&gt;, 从构造函数&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Promise&lt;/code&gt;创建一个新的promise实例

&lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;promise&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;Promise&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kd&quot;&gt;function&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;resolve&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;reject&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// 处理结束后，调用resolve或reject&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h6 id=&quot;instance-method&quot;&gt;&lt;strong&gt;Instance Method&lt;/strong&gt;&lt;/h6&gt;

对通过new生成的promise对象，可以使用&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;promise.then()&lt;/code&gt; 方法来调用&lt;strong&gt;resolve&lt;/strong&gt;或&lt;strong&gt;reject&lt;/strong&gt;的回调函数。

&lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nx&quot;&gt;promise&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;then&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;onFulfilled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;onRejected&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;strong&gt;resolve成功&lt;/strong&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;onFulfilled&lt;/code&gt;会被调用
&lt;strong&gt;reject失败&lt;/strong&gt; &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;onRejected&lt;/code&gt;会被调用

&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;promise.then&lt;/code&gt;成功和失败时都可以使用。在只想对异常进行处理时，可以采用&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;promise.then(undefined, onRejected)&lt;/code&gt;这种方式，只指定reject时的回调函数。不过这种情况下，&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;promise.catch(onRejected)&lt;/code&gt;是个更好的选择。

&lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nx&quot;&gt;promise&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;catch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;onRejected&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h6 id=&quot;static-method&quot;&gt;&lt;strong&gt;Static Method&lt;/strong&gt;&lt;/h6&gt;

Promise包括一些静态方法如&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Promise.all()&lt;/code&gt;，&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Promise.resolve()&lt;/code&gt;等。

&lt;h5 id=&quot;112-promise的三种状态&quot;&gt;&lt;strong&gt;1.1.2 Promise的三种状态&lt;/strong&gt;&lt;/h5&gt;

&lt;table&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;状态&lt;/th&gt;
      &lt;th style=&quot;text-align: center&quot;&gt;描述&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;pending&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;初始状态，既不是成功也不是失败，也就是promise实例刚被创建的初始状态。&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;fulfilled&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;resolve(成功)，此时会调用&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;onFulfilled&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;rejected&lt;/td&gt;
      &lt;td style=&quot;text-align: center&quot;&gt;reject(失败), 此时会调用&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;onRejected&lt;/code&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;

&lt;h5 id=&quot;113-promise示例代码&quot;&gt;&lt;strong&gt;1.1.3 Promise示例代码&lt;/strong&gt;&lt;/h5&gt;

&lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;
&lt;span class=&quot;kd&quot;&gt;function&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;getURL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;URL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;promise&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;Promise&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kd&quot;&gt;function&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;resolve&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;reject&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;kd&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;req&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;XMLHttpRequest&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;();&lt;/span&gt;
        &lt;span class=&quot;nx&quot;&gt;req&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;open&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;'&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;GET&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;URL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
        &lt;span class=&quot;nx&quot;&gt;req&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;onload&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;function&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;req&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;status&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
                &lt;span class=&quot;nx&quot;&gt;resolve&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;req&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;responseText&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
            &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
             &lt;span class=&quot;k&quot;&gt;else&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
                 &lt;span class=&quot;nx&quot;&gt;reject&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;Error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;req&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;statusText&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;));&lt;/span&gt;
             &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;};&lt;/span&gt;
        &lt;span class=&quot;nx&quot;&gt;req&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;onerror&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;function&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;nx&quot;&gt;reject&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;Error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;req&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;statusText&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;));&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;};&lt;/span&gt;
        &lt;span class=&quot;nx&quot;&gt;req&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;send&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;();&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;})&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;URL&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;'&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;http://xxx.xx.txt&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;nx&quot;&gt;getURL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;URL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;then&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kd&quot;&gt;function&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;onFulfilled&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}).&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;catch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kd&quot;&gt;function&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;onRejected&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;error&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;})&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;12-promiseprototype&quot;&gt;&lt;strong&gt;1.2 Promise.prototype&lt;/strong&gt;&lt;/h4&gt;

Promise实例继承自Promise.prototype. 你可以通过构造器的原型对象在所有的Promise实例上添加属性或方法。

&lt;h5 id=&quot;promiseprototypeconstructor&quot;&gt;&lt;strong&gt;Promise.prototype.constructor&lt;/strong&gt;&lt;/h5&gt;

&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Promise.prototype.constructor&lt;/code&gt;表示Promise的构造函数的原型，以便在其原型上放置&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;then()&lt;/code&gt;、&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;catch()&lt;/code&gt;、&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;finally()&lt;/code&gt;方法。

&lt;h5 id=&quot;promiseprototypethenonfulfilled-onrejected&quot;&gt;&lt;strong&gt;Promise.prototype.then(onFulfilled, onRejected)&lt;/strong&gt;&lt;/h5&gt;

为promise添加成功或者失败处理，同时返回一个新的包含解析过后的的值或者处理函数的promise，或者这个原始的未被处理的promise。

&lt;h5 id=&quot;promiseprototypecatchonrejected&quot;&gt;&lt;strong&gt;Promise.prototype.catch(onRejected)&lt;/strong&gt;&lt;/h5&gt;

为promise添加失败的回调处理，如果这个回调函数被调用了，则返回一个包含回调返回值的新的promise，如果这个promise没被处理，则返回原始的值。

&lt;h5 id=&quot;promiseprototypefinallyonfinally&quot;&gt;&lt;strong&gt;Promise.prototype.finally(onFinally)&lt;/strong&gt;&lt;/h5&gt;

为promise添加处理，如果原始的promise对象已经被解析，则返回解析后的promise。无论promise是什么状态，这个处理函数都会被执行。

&lt;h4 id=&quot;promise的静态方法&quot;&gt;&lt;strong&gt;Promise的静态方法&lt;/strong&gt;&lt;/h4&gt;

&lt;h5 id=&quot;promiseresolve&quot;&gt;&lt;strong&gt;Promise.resolve&lt;/strong&gt;&lt;/h5&gt;

一般情况下，我们会使用&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;new Promise()&lt;/code&gt;来创建promise对象，我们也可以使用&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Promise.resolve&lt;/code&gt;或&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Promise.reject()&lt;/code&gt;

例如&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Promise.resolve(42)&lt;/code&gt;，可以认为是以下代码的语法糖:
&lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;Promise&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;resolve&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;nx&quot;&gt;resolve&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;})&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h5 id=&quot;promisealliterable&quot;&gt;&lt;strong&gt;Promise.all(iterable)&lt;/strong&gt;&lt;/h5&gt;

当iterable参数中所有的promises都被resolve时，或参数中不包含promises的时候，&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Promise.all(iterable)&lt;/code&gt;会返回一个单一的Promise。当iterable中有一个promise返回拒绝，all()方法会立即终止并返回第一个被reject的promise对象。

&lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;promise1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;Promise&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;resolve&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;promise2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;42&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;promise3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;Promise&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kd&quot;&gt;function&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;resolve&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;reject&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;nx&quot;&gt;setTimeout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;resolve&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;'&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;foo&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;})&lt;/span&gt;

&lt;span class=&quot;nb&quot;&gt;Promise&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;all&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;promise1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;promise2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;promise3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]).&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;then&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kd&quot;&gt;function&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;values&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;// 3, 42, foo&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;})&lt;/span&gt;

&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h5 id=&quot;promiseraceiterable&quot;&gt;&lt;strong&gt;Promise.race(iterable)&lt;/strong&gt;&lt;/h5&gt;

&lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Promise.race(iterable)&lt;/code&gt;方法返回iterable参数中最先被resolve或者reject的promise对象，包括返回值或者失败原因。

&lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;promise1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;Promise&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;resolve&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;reject&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;nx&quot;&gt;setTimeout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;resolve&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;300&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;'&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;one&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;});&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;promise2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;Promise&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;resolve&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;reject&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;nx&quot;&gt;setTimeout&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;resolve&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;'&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;two&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;});&lt;/span&gt;

&lt;span class=&quot;nb&quot;&gt;Promise&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;race&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;([&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;promise1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;promise2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]).&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;then&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;result&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&amp;gt;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;result&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;&lt;span class=&quot;c1&quot;&gt;// expected 'two'&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;})&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
</description>
        <pubDate>Wed, 28 Mar 2018 00:00:00 +0000</pubDate>
        <link>https://heiguagua.github.io/2018/03/28/js%E5%BC%82%E6%AD%A5%E4%BA%8B%E4%BB%B6%E5%A4%84%E7%90%86/</link>
        <guid isPermaLink="true">https://heiguagua.github.io/2018/03/28/js%E5%BC%82%E6%AD%A5%E4%BA%8B%E4%BB%B6%E5%A4%84%E7%90%86/</guid>
        
        <category>Promise</category>
        
        <category>异步处理</category>
        
        
        <category>Web</category>
        
      </item>
    
      <item>
        <title>js设计模式</title>
        <description>&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#常用的javascript设计模式&quot; id=&quot;markdown-toc-常用的javascript设计模式&quot;&gt;&lt;strong&gt;常用的javascript设计模式&lt;/strong&gt;&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#为什么要使用设计模式&quot; id=&quot;markdown-toc-为什么要使用设计模式&quot;&gt;&lt;strong&gt;为什么要使用设计模式&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#单体模式单例模式&quot; id=&quot;markdown-toc-单体模式单例模式&quot;&gt;&lt;strong&gt;单体模式/单例模式&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#工厂模式&quot; id=&quot;markdown-toc-工厂模式&quot;&gt;&lt;strong&gt;工厂模式&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;常用的javascript设计模式&quot;&gt;&lt;strong&gt;常用的javascript设计模式&lt;/strong&gt;&lt;/h3&gt;
&lt;hr /&gt;

javascript常用的设计模式大概有以下几种：

&lt;ul&gt;
  &lt;li&gt;
    单体模式/单例模式
  &lt;/li&gt;
  &lt;li&gt;
    工厂模式
  &lt;/li&gt;
  &lt;li&gt;
    观察者模式(发布者-订阅者模式)
  &lt;/li&gt;
  &lt;li&gt;
    策略模式
  &lt;/li&gt;
  &lt;li&gt;
    模板模式
  &lt;/li&gt;
  &lt;li&gt;
    代理模式
  &lt;/li&gt;
  &lt;li&gt;
    外观模式
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h4 id=&quot;为什么要使用设计模式&quot;&gt;&lt;strong&gt;为什么要使用设计模式&lt;/strong&gt;&lt;/h4&gt;

使用设计模式是为了让代码可重用性更高，让代码更容易让人理解、保证代码可靠性。

&lt;h4 id=&quot;单体模式单例模式&quot;&gt;&lt;strong&gt;单体模式/单例模式&lt;/strong&gt;&lt;/h4&gt;
&lt;hr /&gt;

单例模式定义了一个对象的创建过程，这个对象只有一个单独的实例，并提供一个访问它的全局访问点。单例保证一个类只有一个实例。实现的方法就是先判断这个实例是否存在，存在则直接返回，不存在则创建一个新的实例再返回。

单例的实现方式有很多种：&lt;br /&gt;
最简单的方式如：

&lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;Singleton&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;function&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;name&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;  
    &lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;instance&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;nx&quot;&gt;Singleton&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;prototype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;getName&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;function&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;nx&quot;&gt;Singleton&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;getInstance&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;function&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;instance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;instance&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt;  &lt;span class=&quot;nx&quot;&gt;Singleton&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;instance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;s1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;Singleton&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;getInstance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;'&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;s1&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;s2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;Singleton&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;getInstance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;'&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;s2&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;

&lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;s1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;===&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;s2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

或者使用闭包形式创建单例模式:

&lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;Singleton&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;function&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;name&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;nx&quot;&gt;Singleton&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;prototype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;getName&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;function&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;nx&quot;&gt;Singleton&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;getInstance&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kd&quot;&gt;function&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;){&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;instance&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;function&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;instance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;nx&quot;&gt;instance&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;Singleton&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;})()&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;Singleton&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;getInstance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;'&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;b&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;Singleton&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;getInstance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;'&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;

&lt;span class=&quot;nx&quot;&gt;console&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;log&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;===&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;b&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;strong&gt;应用场景&lt;/strong&gt;

单例模式是一种常用的设计模式，有一些对象我们只需要一个，比如全局对象等。

&lt;ol&gt;
  &lt;li&gt;
    我们可以借用它来划分命名空间；
  &lt;/li&gt;
  &lt;li&gt;
    借助单例模式，可以把代码组织的更为一致，方便阅读与维护。
  &lt;/li&gt;
&lt;/ol&gt;

&lt;h4 id=&quot;工厂模式&quot;&gt;&lt;strong&gt;工厂模式&lt;/strong&gt;&lt;/h4&gt;

工厂模式的定义：提供创建对象的接口。

应用场景：

&lt;ol&gt;
  &lt;li&gt;
    对象的构建十分复杂
  &lt;/li&gt;
  &lt;li&gt;
    需要依赖具体环境创建不同实例
  &lt;/li&gt;
  &lt;li&gt;
    处理具有大量相同属性的小对象。
  &lt;/li&gt;
&lt;/ol&gt;
</description>
        <pubDate>Fri, 23 Mar 2018 00:00:00 +0000</pubDate>
        <link>https://heiguagua.github.io/2018/03/23/js%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/</link>
        <guid isPermaLink="true">https://heiguagua.github.io/2018/03/23/js%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/</guid>
        
        <category>设计模式</category>
        
        
        <category>Web</category>
        
      </item>
    
      <item>
        <title>前端重要知识点总结</title>
        <description>&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#基础&quot; id=&quot;markdown-toc-基础&quot;&gt;&lt;strong&gt;基础&lt;/strong&gt;&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#__proto__和prototype的区别和关系&quot; id=&quot;markdown-toc-__proto__和prototype的区别和关系&quot;&gt;&lt;strong&gt;__proto__和prototype的区别和关系&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href=&quot;#原型链&quot; id=&quot;markdown-toc-原型链&quot;&gt;&lt;strong&gt;原型链&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;基础&quot;&gt;&lt;strong&gt;基础&lt;/strong&gt;&lt;/h3&gt;
&lt;hr /&gt;

&lt;h4 id=&quot;__proto__和prototype的区别和关系&quot;&gt;&lt;strong&gt;__proto__和prototype的区别和关系&lt;/strong&gt;&lt;/h4&gt;

在了解原型之前，必须先弄清几个概念：

&lt;strong&gt;对象&lt;/strong&gt;

js中的对象分为两种：

&lt;ul&gt;
  &lt;li&gt;
    &lt;strong&gt;普通对象&lt;/strong&gt;

    &lt;ul&gt;
      &lt;li&gt;普通对象：有__proto__属性（指向其构造函数的原型对象），没有prototype属性。&lt;/li&gt;
      &lt;li&gt;原型对象：(Person.prototype 原型对象)，原型对象还有一个constructor属性（指向构造函数对象）&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;strong&gt;函数对象&lt;/strong&gt;

    &lt;ul&gt;
      &lt;li&gt;通过new Function()创建的都是函数对象。函数对象拥有__proto__、prototype属性。Function, Object, Array, Date, String, 自定义函数&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;strong&gt;原型对象&lt;/strong&gt;

    每创建一个函数都会有一个prototype属性，这个属性是一个指针，指向一个对象。原型对象包含特定类型的所有实例共享的属性和方法。
  &lt;/li&gt;
&lt;/ul&gt;

来看看一张比较容易看得懂的图，深度理解对象的原型：

&lt;img src=&quot;/images/prototype.jpg&quot; alt=&quot;&quot; /&gt;

&lt;ol&gt;
  &lt;li&gt;在JS里，万物皆对象。&lt;/li&gt;
&lt;/ol&gt;

方法（Function）是对象，方法的原型（Function.prototype）是对象。

对象具有__proto__属性，可称为隐式原型，一个对象的隐式原型指向构造该对象的构造函数的原型，这样保证了实例能够访问在构造函数原型中定义的属性和方法。

&lt;ol&gt;
  &lt;li&gt;方法（Function）&lt;/li&gt;
&lt;/ol&gt;

方法也是对象，除了和其他对象一样拥有__proto__属性之外，还有自己特有的属性—-原型属性(prototype)。这个属性是一个指针，指向一个对象（及原型对象），这个对象包含了所有实例共享的属性和方法。原型对象也有一个属性，叫做constructor，这个属性包含了一个指针，指回原构造函数。

再来看看上面那张图：

&lt;ol&gt;
  &lt;li&gt;Foo() 构造函数&lt;/li&gt;
&lt;/ol&gt;

构造函数Foo()的原型属性Foo.prototype指向原型对象，在原型对象里有共有的属性和方法，所有构造函数声明的实例（这里是f1, f2）都可以共享这个方法。

&lt;ol&gt;
  &lt;li&gt;原型对象Foo.prototype&lt;/li&gt;
&lt;/ol&gt;

Foo.prototype保存这实例共享的方法，有一个指回构造函数的指针constructor.

&lt;ol&gt;
  &lt;li&gt;对象实例f1, f2&lt;/li&gt;
&lt;/ol&gt;

f1, f2是对象Foo的实例，对象的实例有__proto__属性，指向对象的构造函数的原型对象，这样就可以访问原型对象的所有方法了。

BTW，Foo()构造函数除了是方法，也是对象(&lt;strong&gt;函数对象&lt;/strong&gt;)，也有__proto__属性，那么这个__proto__指向谁呢？

函数的__proto__属性指向函数的构造函数的原型对象。函数的构造函数就是Function，因此，函数的__proto__属性指向Function.prototype.

除了Foo(), Function()和Object()都是一样的道理。

原型对象也是对象，那它（比如，Foo.prototype，Function.prototype）的__proto__属性指向谁呢？

同理，指向它的构造函数的原型对象，这里是Object.prototype。

最后，Object.prototype的__proto__属性指向null。

总结：

&lt;strong&gt;1. 对象有属性__proto__，它指向对象的构造函数的原型对象。&lt;/strong&gt;

&lt;strong&gt;2. 函数有prototype属性，函数的prototype属性指向函数的原型对象，因为函数也是对象，函数的__proto__同样指向函数的构造函数的原型对象。&lt;/strong&gt;

&lt;h4 id=&quot;原型链&quot;&gt;&lt;strong&gt;原型链&lt;/strong&gt;&lt;/h4&gt;

首先，看一张图了解一下实例、原型对象和构造函数之间的关系。

&lt;img src=&quot;/images/proto_constructor.png&quot; alt=&quot;&quot; /&gt;

从上图可以看出，每个构造函数都有一个原型对象，原型对象包含一个指向构造函数的指针（constructor），而实例对象都包含一个指向原型对象的__prototype__内部指针。

如果让原型对象等于另一个类型的实例，那么此时的原型对象将包含一个指向另一个原型对象的（&lt;strong&gt;proto&lt;/strong&gt;）指针，另一个原型对象也包含指向另一个构造函数的指针（constructor）。加入

另一个原型又是另一个类型的实例。。。。。。这就构成了实例与原型的链条。也就是原型链。

看图：

&lt;img src=&quot;/images/prototype-chain.png&quot; alt=&quot;&quot; /&gt;

举例说明：

&lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;function&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;Animal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;type&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;dl&quot;&gt;'&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;animal&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;nx&quot;&gt;Animal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;prototype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;getType&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;function&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;type&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;function&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;Dog&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;this&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;name&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;'&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;wangwang&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;nx&quot;&gt;Dog&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;prototype&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;Animal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;();&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;wangcai&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;new&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;Dog&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;();&lt;/span&gt;

&lt;span class=&quot;nx&quot;&gt;wangcai&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;getType&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;();&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// 'animal'&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;// 原型链的关系:&lt;/span&gt;
&lt;span class=&quot;nx&quot;&gt;wangcai&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;__proto__&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;===&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;Dog&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;prototype&lt;/span&gt;
&lt;span class=&quot;nx&quot;&gt;Dog&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;prototype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;__proto__&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;===&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;Animal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;prototype&lt;/span&gt;
&lt;span class=&quot;nx&quot;&gt;Animal&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;prototye&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;__proto__&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;===&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;Object&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;prototype&lt;/span&gt;
&lt;span class=&quot;nb&quot;&gt;Object&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;prototype&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;__proto__&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;===&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;null&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;strong&gt;js中实现继承主要依靠原型链查找&lt;/strong&gt;

原型继承（&lt;strong&gt;&lt;em&gt;prototype-based inheritance&lt;/em&gt;&lt;/strong&gt;）的步骤大概是这样：

&lt;ol&gt;
  &lt;li&gt;
    每一个函数F都有一个原型对象（prototype）F.prototype
  &lt;/li&gt;
  &lt;li&gt;
    每一个函数都可以通过new 关键字来创建一个类构造函数，new F()会产一个一个对象O
  &lt;/li&gt;
  &lt;li&gt;
    在调用对象的某个属性和方法时，比如O.xxx, 首先会查找这个对象自身有没有这个属性或者方法，没有就会去（&lt;strong&gt;这个对象的构造函数的原型对象中查找&lt;/strong&gt;），也就是找O的构造函数F的原型对象F.prototype.xxx。
  &lt;/li&gt;
  &lt;li&gt;
    原型对象F.prototype.xxx也是一个对象，查找F.prototype.xxx会重复步骤3.
  &lt;/li&gt;
&lt;/ol&gt;
</description>
        <pubDate>Wed, 21 Mar 2018 00:00:00 +0000</pubDate>
        <link>https://heiguagua.github.io/2018/03/21/js%E5%8E%9F%E5%9E%8B%E5%8F%8A%E5%8E%9F%E5%9E%8B%E9%93%BE/</link>
        <guid isPermaLink="true">https://heiguagua.github.io/2018/03/21/js%E5%8E%9F%E5%9E%8B%E5%8F%8A%E5%8E%9F%E5%9E%8B%E9%93%BE/</guid>
        
        <category>概览</category>
        
        
        <category>Web</category>
        
      </item>
    
      <item>
        <title>AMD&amp;CMD</title>
        <description>&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#amdcmd规范&quot; id=&quot;markdown-toc-amdcmd规范&quot;&gt;&lt;strong&gt;AMD&amp;amp;CMD规范&lt;/strong&gt;&lt;/a&gt;    &lt;ul&gt;
      &lt;li&gt;&lt;a href=&quot;#js模块化编程&quot; id=&quot;markdown-toc-js模块化编程&quot;&gt;&lt;strong&gt;JS模块化编程&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;amdcmd规范&quot;&gt;&lt;strong&gt;AMD&amp;amp;CMD规范&lt;/strong&gt;&lt;/h3&gt;
&lt;hr /&gt;

&lt;h4 id=&quot;js模块化编程&quot;&gt;&lt;strong&gt;JS模块化编程&lt;/strong&gt;&lt;/h4&gt;
&lt;hr /&gt;

随着前端开发的不断发展，互联网业务的复杂度越来越高，JS模块化开发已经变得越来越重要。

我们在前端开发过程中，使用统一的编写方式进行模块化，可以对巨大系统和复杂业务的代码进行很好的组织和管理，方便多人的合作。

JS中的模块化规范包括（&lt;strong&gt;CommonJS, AMD, CMD&lt;/strong&gt;）。

&lt;strong&gt;（1）CommonJS&lt;/strong&gt;

&lt;em&gt;CommonJS是一个有志于构建Javascript生态圈的组织。整个社区致力于提高javascript程序的可移植性和可交换性，无论是在服务端还是浏览器端。&lt;/em&gt;

&lt;em&gt;a group with a goal of building up the javascript ecosystem for web browsers, desktop and command line apps and in the browser.&lt;/em&gt;

CommonJS是一个更偏向于服务器端的规范。Node.js采用了这个规范。根据CommonJS规范，一个单独的文件就是一个模块。

CommonJS规范的主要内容：模块必须通过module.exports导出对应的变量或接口，通过require()导入其他模块的输出到当前模块。

&lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;// moduleA.js&lt;/span&gt;
&lt;span class=&quot;nx&quot;&gt;module&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;exports&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;function&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nx&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;  
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;++&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;;&lt;/span&gt;  
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;div class=&quot;language-js highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;// moduleB.js&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;moduleA&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;require&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;'&lt;/span&gt;&lt;span class=&quot;s1&quot;&gt;./moduleA&lt;/span&gt;&lt;span class=&quot;dl&quot;&gt;'&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;  
&lt;span class=&quot;kd&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;result&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nx&quot;&gt;moduleA&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;);&lt;/span&gt;  
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;strong&gt;优点&lt;/strong&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;* 便于服务器端重用  

* NPM中已经提供近20W个模块包   

* 简单并容易使用
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;strong&gt;缺点&lt;/strong&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;* 使用同步的方式加载资源，阻塞加载，不适合在浏览器环境中使用。

* 不能非阻塞的并行加载多个模块
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

</description>
        <pubDate>Tue, 20 Mar 2018 00:00:00 +0000</pubDate>
        <link>https://heiguagua.github.io/2018/03/20/AMD&CMD/</link>
        <guid isPermaLink="true">https://heiguagua.github.io/2018/03/20/AMD&CMD/</guid>
        
        <category>规范</category>
        
        <category>AMD</category>
        
        <category>CMD</category>
        
        
        <category>Web</category>
        
      </item>
    
      <item>
        <title>前端组件化开发</title>
        <description>&lt;ul id=&quot;markdown-toc&quot;&gt;
  &lt;li&gt;&lt;a href=&quot;#前端组件化开发&quot; id=&quot;markdown-toc-前端组件化开发&quot;&gt;&lt;strong&gt;前端组件化开发&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3 id=&quot;前端组件化开发&quot;&gt;&lt;strong&gt;前端组件化开发&lt;/strong&gt;&lt;/h3&gt;
&lt;hr /&gt;

随着前端生态jade、less、scss、typescript和webpack等工具的完善，前端组件化开发效率已经有了很大的提升。

特别是像Ant Design、Element UI、iView这些优秀的前端组件库的流行，更是将组件化开发效率发挥到了极致。特别是在做管理系统的页面，脚手架的搭建、添加依赖包、配置路由、创建页面、引入组建，很快就可以搭建一个系统。

&lt;strong&gt;什么是前端组件化开发&lt;/strong&gt;

可能你遇到过这种情况，一个页面的js文件可能包含几百甚至上千行代码。这种代码又臭又长，读懂已经很难了，更别说维护。

这个时候就需要利用组件化开发，进行功能拆分，封装组件，单独维护。

前端组件化开发就是将页面的某一部分独立出来，将这一部分的数据层（Model），视图层（View），控制层（Controller）用黑盒的形式全部封装到一个组件内，然后暴露一些开箱即用的属性和函数供外部组件调用。

一个前端组件，包含了html、css、javascript，基本上涵盖了组件的所有内容。外部只要按照组件设定的属性、函数及事件处理进行调用即可，完全不比考虑内部实现逻辑。组件是一个完全的黑盒。

有一些比较常用的前端组件，如vue-router、vuex、react-router，redux等，都是基于Vue和React的组件，它们只专注于路由、状态存储的工作，并且把这些事情做好。

只要利用好组件化开发，开发一个页面就像搭积木一样，将各个组件拼接到一起，最后融合到一起就是一个完整的系统。

&lt;strong&gt;组件化开发的优点&lt;/strong&gt;

降低系统各个功能的耦合性，提高了功能内部的聚合性，降低开发复杂度，提高开发效率。

&lt;strong&gt;如何设计一个组件&lt;/strong&gt;

&lt;strong&gt;专一&lt;/strong&gt;

一个组件只专注做一件事情，并且把这件事做好

&lt;strong&gt;可配置型&lt;/strong&gt;

&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;组件除了要展示默认的内容，还需要做一些动态的适配，最基本的方式是通过属性向组件传递配置的值，然后在组件初始化的生命周期内，通过读取属性的值做对应的修改；还有一些方法，通过调用组件暴露的函数向函数传递有效的值；向组件传递特定事件，并在组件内监听该事件。

在做可配置性时，为了让组件更健壮，保证组件接收到的是有效的属性和参数。
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;strong&gt;组件的生命周期&lt;/strong&gt;

一个组件，需要明确知道在生命周期的不同阶段做该做的事。

React提供了一些生命周期函数：componentWillMount, conponentDidMount, componentWillRecieveProps, 
shouldComponentUpdate, componentWillUpdate, componentDidUpdate, render, componentWillUnmount,…

Vue中提供了一些生命周期函数：beforeCreate, created, beforeMount, mounted, beforeUpdate, updated, beforeDestroy, destroyed,…
</description>
        <pubDate>Thu, 15 Mar 2018 00:00:00 +0000</pubDate>
        <link>https://heiguagua.github.io/2018/03/15/%E5%89%8D%E7%AB%AF%E7%BB%84%E4%BB%B6%E5%8C%96%E5%BC%80%E5%8F%91/</link>
        <guid isPermaLink="true">https://heiguagua.github.io/2018/03/15/%E5%89%8D%E7%AB%AF%E7%BB%84%E4%BB%B6%E5%8C%96%E5%BC%80%E5%8F%91/</guid>
        
        <category>组件化</category>
        
        
        <category>Web</category>
        
      </item>
    
  </channel>
</rss>
