微信小程序底层的实现原理是怎样的?

用到了哪些技术?
关注者
660
被浏览
204,021
登录后你可以
不限量看优质回答私信答主深度交流精彩内容一键收藏

作者:phodal

链接:

zhuanlan.zhihu.com/p/22

来源:知乎

著作权归作者所有,转载请联系作者获得授权。

本来想的是昨天晚上写这篇文章的,后来昨天在写一个Cordova上的iOS插件的时候各种不顺。对接的第三方SDK不给力,于是六点多回到家的时候,我就就开始娱乐了,哈哈哈~~

其实这篇文章应该算是一篇拾遗。

从map组件说起

在今天公布的开发文档里,我们知道使用一个地图组件的时候是这样子的:


<map longitude="23.099994" latitude="113.324520" markers="{{markers}}" covers="{{covers}}" style="width: 375px; height: 200px;"></map>

在之前的文件里,我们提到过这个文件是wxml文件,然后我们要用wxcc将其转换为virtual dom中的方法,如:


./wcc -d map.xml

它就会返回一个js的方法,如:


/*v0.7cc_20160919*/
var $gwxc
var $gaic={}
$gwx=function(path,global){
function _(a,b){b&&a.children.push(b);}
function _n(tag){$gwxc++;if($gwxc>=16000){throw 'enough, dom limit exceeded, you don\'t do stupid things, do you?'};return {tag:tag.substr(0,3)=='wx-'?tag:'wx-'+tag,attr:{},children:[]}}
function _s(scope,env,key){return typeof(scope[key])!='undefined'?scope[key]:env[key]}
...

插播一句:上面有一个count,很有意思$gwxc > 16000,这个就是dom数的count。超了就来个异常:enough, dom limit exceeded, you don't do stupid things, do you?,中文意思就是:你个愚蠢的人类,你是一个前端开发人员吗?

随后,在浏览器里调试一下:


JSON.stringify($gwx('map.wxml')('test'))

在小程序中是要这样调用的:


        document.dispatchEvent(new CustomEvent("generateFuncReady", {
            detail: {
                generateFunc: $gwx('map.wxml')
            }
        }))

就会返回下面的结果:


{
    "children": [
        {
            "attr": {
                "covers": "",
                "latitude": "113.324520",
                "longitude": "23.099994",
                "markers": "",
                "style": "width: 375px; height: 200px;"
            },
            "children": [],
            "tag": "wx-map"
        }
    ],
    "tag": "wx-page"
}

看来这个名为wx-map的标签就是微信下的map标签,它是wx-page的children。然后让我们在WAWebview中搜索一下,就会发现一个很有意思的代码:


{
    is: "wx-map",
    behaviors: ["wx-base", "wx-native"],
    template: '<div id="map" style="width: 100%; height: 100%;"></div>',
    properties: {
        latitude: {type: Number, reflectToAttribute: !0, observer: "latitudeChanged", value: 39.92},
        longitude: {type: Number, reflectToAttribute: !0, observer: "longitudeChanged", value: 116.46},
        scale: {type: Number, reflectToAttribute: !0, observer: "scaleChanged", scale: 16},
        markers: {type: Array, value: [], reflectToAttribute: !1, observer: "markersChanged"},
        covers: {type: Array, value: [], reflectToAttribute: !1, observer: "coversChanged"},
        _mapId: {type: Number}
  }

它的behaviors中有一句:wx-native,这莫非就是传说中的native组件:

顺便再看一个video是不是也是一样的:


{
    is: "wx-video",
    behaviors: ["wx-base", "wx-player", "wx-native"],
    template: '<div class="container">\n    <video id="player" webkit-playsinline style="display: none;"></video>\n    <div id="default" class="bar" style="display: none;">\n      <div id="button" class$="button {{_buttonType}}"></div>\n      <div class="time currenttime" parse-text-content>{{_currentTime}}</div>\n      <div id="progress" class="progress">\n        <div id="ball" class="ball" style$="left: {{_progressLeft}}px;">\n          <div class="inner"></div>\n        </div>\n        <div class="inner" style$="width: {{_progressLength}}px;"></div>\n      </div>\n      <div class="time duration" parse-text-content>{{_duration}}</div>\n      <div id="fullscreen" class="fullscreen"></div>\n    </div>\n  </div>\n  <div id="fakebutton"></div>',
    properties: {
        _videoId: {type: Number},
        _progressLeft: {type: Number, value: -22},
        _progressLength: {type: Number, value: 0}
}

好了,你那么聪明,我就这么说一半好了,剩下你自己去猜。

可以肯定的是:

  • map标签在开发的时候会变成HTML + CSS
  • map标签在微信上可以使用类似于Cordova的形式调用 Native组件

再接着说,virtual dom的事,回到示例代码里的map.js:


Page({
  data: {
    markers: [{
      latitude: 23.099994,
      longitude: 113.324520,
      name: 'T.I.T 创意园',
      desc: '我现在的位置'
    }],
    covers: [{
      latitude: 23.099794,
      longitude: 113.324520,
      icaonPath: '../images/car.png',
      rotate: 10
    }, {
      latitude: 23.099298,
      longitude: 113.324129,
      iconPath: '../images/car.png',
      rotate: 90
    }]
  }
})

js里只放置了data,剩下的都是依据上面的值变动的observer,如:

  • _updatePosition
  • _hiddenChanged
  • latitudeChanged
  • longitudeChanged
  • scaleChanged
  • coversChanged
  • ...

这种代码的感觉比React更进了一步的节奏,本来你还需要编码来观察state,现在只需要state变动了就可以了。。。23333....,你们这些程序员都会被fire的。

好了,这里差不多就这样了~~。

重新审视WXWebview.js

于是,我重新逛逛WXWebview.js,发现这个文件里面不只有component的内容,还有:

  • reportSDK
  • webviewSDK ??
  • virtual_dom
  • exparser
  • wx-components.js
  • wx-components.css

等等,你是不是已经猜到我在说什么了,上一篇中我们说到了PageFrame:


  <!-- percodes -->
  <!--{{WAWebview}}-->
  <!--{{reportSDK}}-->
  <!--{{webviewSDK}}-->
  <!--{{exparser}}-->
  <!--{{components_js}}-->
  <!--{{virtual_dom}}-->
  <!--{{components_css}}-->
  <!--{{allWXML}}-->
  <!--{{eruda}}-->
  <!--{{style}}-->
  <!--{{currentstyle}}-->
  <!--{{generateFunc}}-->

在之前的想法里,我觉得我必须要集齐上面的SDK,才能招唤中神龙。后来,我看到了这句:


isDev ? {
        "<!--{{reportSDK}}-->": "reporter-sdk.js",
        "<!--{{webviewSDK}}-->": "webview-sdk.js",
        "<!--{{virtual_dom}}-->": "virtual_dom.js",
        "<!--{{exparser}}-->": "exparser.js",
        "<!--{{components_js}}-->": "wx-components.js",
        "<!--{{components_css}}-->": "wx-components.css"
    } : {"<!--{{WAWebview}}-->": "WAWebview.js"}

如果不是开发环境就使用WAWebview.js,在开发环境中使用使用xxSDK,那么生产环境是怎么回事?如果是在开发环境会去下载最新的SDK,好像不对~~,哈哈。。

我猜这部分,我需要一个内测id,才能猜出这个答案。

有意思的是,IDE会对比version.json,然后去获取最新的,用于预览?


{
  "WAService.js": 2016092000,
  "WAWebview.js": 2016092000,
  "wcc": 2016092000,
  "wcsc": 2016092000
}

上面已经解释清楚了WAWebview的功能了,那么WAService.js呢——就是封装那些API的,如downloadFile:


uploadFile: function (e) {
    u("uploadFile", e, {url: "", filePath: "", name: ""}) && (0, s.invokeMethod)("uploadFile", e)
}, downloadFile: function (e) {
    u("downloadFile", e, {url: ""}) && (0, s.invokeMethod)("downloadFile", e)
}

这一点上仍然相当有趣,在我们开发的时候仍然是WAWebview做了相当多的事,而它和WAService的打包是分离的。

那么,我们从理论上来说,只需要有WAWebview就可以Render页面了。