Home >WeChat Applet >Mini Program Development >Analyze the implementation principles of small programs
Overview
As a front-end developer, if you are still at the application development level, then you are OUT Okay, come and discuss with me some technical details of the underlying implementation of the mini program framework itself. Let us have a deep understanding of the mini program's operating mechanism.
Mini programs are a set of frameworks based on WEB specifications, using HTML, CSS and JS. WeChat officially gave them a very cool name: WXML, WXSS, but in essence they are still under the entire WEB system. Constructed.
WXML, I personally guess that this name is derived from WeChat’s Xml. In the final analysis, it is a subset of xml. WXML uses a small number of tags WXSS customized by WeChat, which you can understand as customized CSS. The JS that implements the logical part is still a common ES specification, and the runtime is still Webview (IOS WKWEBVIEW, ANDROID X5).
(Study recommendation: 小program development tutorial)
小program
Mini program directory structure
A complete mini program mainly consists of the following parts:
A Entry file: app.js
A global style: app.wxss
A global configuration: app.json
Page: Under pages, each page is divided by folder, each page has 4 files
View: wxml, wxss
Logic: js, json (page configuration, not required)
Note: pages can also be divided into subdirectories and grandchild directories based on modules, which only need to be in app.json Just fill in the path when registering.
Mini program packaging
After the development is completed, we can click the button visualized here to directly package, upload and publish it. After the review is passed, users can search for it.
So how is packaging implemented?
This involves the implementation principles and methods of this editor. It itself is also implemented based on the WEB technology system, nwjs react, what is nwjs: simply speaking, it is node webkit, node provides us with local api capabilities, and Webkit provides us with web capabilities, and the combination of the two allows us to implement local applications using JS HTML.
Since there is nodejs, the functions in the packaging options above can be easily realized.
ES6 to ES5: Introduce the node package of babel-core
CSS completion: Introduce the node package of postcss and autoprefixer (see the principles of postcss and autoprefixer here)
Code compression: Introduce the node package of uglifyjs
Note: The x5 kernel used on Android does not support ES6 well. If you want to be compatible, you must either use ES5 syntax or introduce the babel-polyfill compatibility library.
The packaged directory structure
The packaged structure of the mini program is as follows:
All mini programs are basically the last They are all typed into the above structure
1. WAService.js framework JS library, which provides basic API capabilities for the logic layer
2. WAWebview.js framework JS library, which provides basic API capabilities for the view layer
3. WAConsole.js framework JS library, console
4. app-config.js Mini program complete configuration, including all configurations we passed in app.json, combined with the default configuration type
5. app-service. js Our own JS code is all packaged into this file
6. page-frame.html is the template file of the applet view. All pages are loaded and rendered using this, and all WXML is disassembled into JS for packaging. Here
7. Pages All pages. This is not our previous wxml file. It mainly handles WXSS conversion and inserts it into the header area using js.
mini program architecture
The framework of the WeChat mini program consists of two parts: the View layer and the App Service logic layer. The View layer is used to render the page structure, and the AppService layer is used to render the page structure. Logical processing, data requests, and interface calls are run in two processes (two Webviews).
The view layer and the logic layer communicate through the JSBridage of the system layer. The logic layer notifies the view layer of data changes and triggers page updates in the view layer. The view layer notifies the triggered events to the logic layer for business processing.
Mini program architecture diagram:
When the mini program starts, it will download the complete package of the mini program from the CDN, which is usually named numerically, such as: _-2082693788_4.wxapkg
Mini Program Technology Implementation
The UI view and logical processing of the mini program are implemented using multiple webviews. The JS code for logical processing is all loaded into one Webview, called AppService. There is only one entire mini program, and it resides in memory throughout its life cycle. All views (wxml and wxss) are hosted by separate Webviews, called AppView. Therefore, when a small program is opened, there will be at least 2 webview processes. Officially, because each view is an independent webview process, considering the performance consumption, the small program is not allowed to open more than 5 levels of pages. Of course, it is also for the sake of experience. better.
AppService
It can be understood that AppService is a simple page. Its main function is to be responsible for the execution of the logical processing part. The bottom layer provides a WAService.js file to provide various The api interface mainly consists of the following parts:
The message communication package is WeixinJSBridge (the development environment is window.postMessage, under IOS it is window.webkit.messageHandlers.invokeHandler.postMessage of WKWebview, under android WeixinJSCore.invokeHandler is used)
1. Log component Reporter encapsulation
2. API methods under wx object
3. Global App, Page, getApp, getCurrentPages and other global methods
4. There are also AMD module specifications Implementation
Then the entire page is to load a bunch of JS files, including the mini program configuration config, the WAService.js above (asdebug.js in debug mode), and the rest are all the js files we wrote ourselves , loaded all at once.
In the development environment
1. Page template: app.nw/app/dist/weapp/tpl/appserviceTpl.js
2. Configuration information, It is directly written to a js variable, __wxConfig.
3. Other configurations
Online environment
After going online, the application part will be packaged into 2 files, named app -config.json and app-service.js, and then WeChat will open the webview to load. For the online part, WeChat itself should have provided the corresponding template file, but it was not found in the compressed package.
1. WAService.js (underlying support)
2. app-config.json (application configuration)
3. app-service.js (application logic)
Then run in JavaScriptCore Inside the engine.
AppView
This can be understood as an h5 page that provides UI rendering. The bottom layer provides a WAWebview.js to provide the underlying functions, as follows:
1 , The message communication package is WeixinJSBridge (the development environment is window.postMessage, under IOS it is window.webkit.messageHandlers.invokeHandler.postMessage of WKWebview, under android WeixinJSCore.invokeHandler is used)
2. Log component Reporter package
3. The api under the wx object is not the same as that in WAService. There are a few functions that are similar to those there, but most of them are methods related to processing UI display
4. Implementation and registration of small program components
5. VirtualDOM, Diff and Render UI implementation
6. Page event triggering
On this basis, AppView has an html template file, through which a specific page is loaded. This template mainly One method, $gwx, mainly returns the VirtualDOM of the specified page. When packaging, the WXML of all pages will be converted into VirtualDOM in advance and put into the template file. WeChat itself wrote two tools wcc (convert WXML to VirtualDOM) and wcsc (convert WXSS into a JS string and append it to the header through the style tag).
Service and View communication
Use message publish and subscribe mechanisms to implement communication between two Webviews. The implementation method is to uniformly encapsulate a WeixinJSBridge object, and different environments The encapsulated interfaces are different, and the specific implementation technology is as follows:
windows environment
is implemented through window.postMessage (use the chrome extension interface to inject a contentScript.js, which It encapsulates the postMessage method to realize communication between webviews, and also provides an interface for directly operating chrome native methods through chrome.runtime.connect method)
Send message: window.postMessage(data, '*' ); // Specify webviewID
in data to receive messages: window.addEventListener('message', messageHandler); // Message processing and distribution also supports calling the native capabilities of nwjs.
I saw a sentence in contentScript, which confirmed that appservice is also implemented through a webview. The implementation principle is the same as that of view, but the business logic processed is different.
'webframe' === b ? postMessageToWebPage(a) : 'appservice' === b && postMessageToWebPage(a)
IOS
Through window.webkit.messageHandlers.NAME.postMessage of WKWebview, two handler message processors are implemented in the WeChat navite code:
invokeHandler : Call native capabilities
publishHandler: Message distribution
is implemented through WeixinJSCore.invokeHanlder. This WeixinJSCore is the interface provided by WeChat for JS calls (native implementation)
invokeHandler: Call native capabilities
publishHandler: Message distribution
WeChat component
В WAWebview.js есть объект под названием exparser, который полностью реализует компоненты мини-программы. Глядя на конкретный метод реализации, идея аналогична спецификации веб-компонентов w3c, но конкретная реализация отличается. Мы Все используемые компоненты будут заранее зарегистрированы, заменены и собраны при рендеринге в Webview.
У exparser есть основной метод:
regiisterBehavior: зарегистрируйте некоторые базовые поведения компонента, чтобы компонент мог его наследовать
RegisterElement: зарегистрируйте компонент, интерфейс, который с нами взаимодействует, в основном представляет собой свойства и события
Компонент инициирует событие (с webviewID), вызывает интерфейс WeixinJSBridge, публикует его в нативном формате, а затем нативный распространяет его в метод обработки события регистрации страницы с указанным webviewID в AppService. слой.
Резюме
Нижний уровень мини-программы по-прежнему основан на Webview, и никаких новых технологий не было изобретено.Вся система фреймворка относительно понятна и проста, на основе веб-спецификаций, гарантируя, что Чтобы максимизировать ценность существующих навыков, вам нужно только понять спецификации платформы, чтобы использовать существующие веб-технологии для разработки. Легко понять и развивать.
MSSM: логика и пользовательский интерфейс полностью изолированы. Это существенно отличается от популярных в настоящее время реакций, agular и vue. Логика апплета и пользовательский интерфейс полностью выполняются на двух отдельных платформах Webview, следующие кадры все еще выполняются в веб-просмотре. При желании вы по-прежнему можете напрямую управлять объектом DOM и выполнять рендеринг пользовательского интерфейса.
Механизм компонентов: Внедрение механизма компонентов, но он не полностью основан на разработке компонентов. Как и vue, большая часть пользовательского интерфейса по-прежнему представляет собой шаблонный рендеринг. Введение механизма компонентов может лучше стандартизировать модель разработки. , а также более удобно обновлять и обслуживать.
Несколько элементов управления: одновременно можно открыть не более 5 окон, размер упакованного файла не может превышать 1 МБ, количество объектов dom не может превышать 16 000 и т. д. Это все для того, чтобы обеспечить лучший опыт.
Соответствующие рекомендации по бесплатному обучению: Руководство по разработке мини-программ WeChat
The above is the detailed content of Analyze the implementation principles of small programs. For more information, please follow other related articles on the PHP Chinese website!