採用React編寫小程式的Remax框架的編譯流程解析(推薦)
Remax是螞蟻開源的一個用React來開發小程式的框架,採用執行時無語法限制的方案。整體研究下來主要分為三大部分:執行時原理、模板渲染原理、編譯流程;看了下現有大部分文章主要集中在Reamx的執行時和模板渲染原理上,而對整個React程式碼編譯為小程式的流程介紹目前還沒有看到,本文即是來補充這個空白。
關於模板渲染原理看這篇文章:https://www.jb51.net/article/132635.htm
關於remax執行時原理看這篇文章:https://www.jb51.net/article/210293.htm
關於React自定義渲染器看這篇文章:https://www.jb51.net/article/198425.htm
Remax的基本結構:
1、remax-runtime 執行時,提供自定義渲染器、宿主元件的包裝、以及由React元件到小程式的App、Page、Component的配置生成器
// 自定義渲染器 export { default as render } from './render'; // 由app.js到小程式App構造器的配置處理 export { default as createAppConfig } from './createAppConfig'; // 由React到小程式Page頁面構造器的一系列適配處理 export { default as createPageConfig } from './createPageConfig'; // 由React元件到小程式自定義元件Component構造器的一系列適配處理 export { default as createComponentConfig } from './createComponentConfig'; // export { default as createNativeComponent } from './createNativeComponent'; // 生成宿主元件,比如小程式原生提供的View、Button、Canvas等 export { default as createHostComponent } from './createHostComponent'; export { createPortal } from './ReactPortal'; export { RuntimeOptions,PluginDriver } from '@remax/framework-shared'; export * from './hooks'; import { ReactReconcilerInst } from './render'; export const unstable_batchedUpdates = ReactReconcilerInst.batchedUpdates; export default { unstable_batchedUpdates,};
2、remax-wechat 小程式相關介面卡
template模板相關,與模板相關的處理原則及原理可以看這個https://www.jb51.net/article/145552.htm
templates // 與渲染相關的模板
src/api 適配與微信小程式相關的各種全域性api,有的進行了promisify化
import { promisify } from '@remax/framework-shared'; declare const wx: WechatMiniprogram.Wx; export const canIUse = wx.canIUse; export const base64ToArrayBuffer = wx.base64ToArrayBuffer; export const arrayBufferToBase64 = wx.arrayBufferToBase64; export const getSystemInfoSync = wx.getSystemInfoSync; export const getSystemInfo = promisify(wx.getSystemInfo);
src/types/config.ts 與小程式的Page、App相關配置內容的適配處理
/** 頁面配置檔案 */ // reference: https://developers.weixin.qq.com/miniprogram/dev/reference/configuration/page.html export interface PageConfig { /** * 預設值:#000000 * 導航欄背景顏色,如 #000000 */ navigationBarBackgroundColor?: string; /** * 預設值:white * 導航欄標題顏色,僅支援 black / white */ navigationBarTextStyle?: 'black' | 'white'; /** 全域性配置檔案 */ // reference: https://developers.weixin.qq.com/miniprogram/dev/reference/configuration/app.html export interface AppConfig { /** * 頁面路徑列表 */ pages: string[]; /** * 全域性的預設視窗表現 */ window?: { /** * 預設值:#000000 * 導航欄背景顏色,如 #000000 */ navigationBarBackgroundColor?: string; /** * 預設值: white * 導航欄標題顏色,僅支援 black / white */ navigationBarTextStyle?: 'white' | 'black';
src/types/component.ts 微信內建元件相關的公共屬性、事件等屬性適配
import * as React from 'react'; /** 微信內建元件公共屬性 */ // reference: https://developers.weixin.qq.com/miniprogram/dev/framework/view/component.html export interface BaseProps { /** 自定義屬性: 元件上觸發的事件時,會發送給事件處理函式 */ readonly dataset?: DOMStringMap; /** 元件的唯一標示: 保持整個頁面唯一 */ id?: string; /** 元件的樣式類: 在對應的 WXSS 中定義的樣式類 */ className?: string; /** 元件的內聯樣式: 可以動態設定的內聯樣式 */ style?: React.cssProperties; /** 元件是否顯示: 所有元件預設顯示 */ hidden?: boolean; /** 動畫物件: 由`wx.createAnimation`建立 */ animation?: Array<Record<string,any>>; // reference: https://develhttp://www.cppcns.comopers.weixin.qq.com/miniprogram/dev/framework/view/wxml/event.html /** 點選時觸發 */ onTap?: (event: TouchEvent) => void; /** 點選時觸發 */ onClick?: (event: TouchEvent) => void; /** 手指觸控動作開始 */ onTouchStart?: (event: TouchEvent) => void;
src/hostComponents 針對微信小程式宿主元件的包裝和適配;node.ts是將小程式相關屬性適配到React的規範
export const alias = { id: 'id',className: 'class',style: 'style',animation: 'animation',src: 'src',loop: 'loop',controls: 'controls',poster: 'poster',name: 'name',author: 'author',onError: 'binderror',onPlay: 'bindplay',onPause: 'bindpause',onTimeUpdate: 'bindtimeupdate',onEnded: 'bindended',}; export const props = Object.values(alias);
各種元件也是利用createHostComponent生成
import * as React from 'react'; import { createHostComponent } from '@remax/runtime'; // 微信已不再維護 export const Audio: React.ComponentType = createHostComponent('audio');
createHostComponent生成React的Element
import * as React from 'react'; import { RuntimeOptions } from '@remax/framework-shared'; export default function createHostComponent<P = any>(name: string,component?: React.ComponentType<P>) { if (component) { return component; } const Component = React.forwardRef((props,ref: React.Ref<any>) => { const { children = [] } = props; let element = React.createElement(name,{ ...props,ref },children); element = RuntimeOptions.get('pluginDriver').onCreateHostComponentElement(element) as React.DOMElement<any,any>; return element; }); return RuntimeOptions.get('pluginDriver').onCreateHostComponent(Component); }
3、remax-macro 按照官方描述是基於babel-plugin-macros的巨集;所謂巨集是在編譯時進行字串的靜態替換,而javascript沒有編譯過程,babel實現巨集的方式是在將程式碼編譯為ast樹之後,對ast語法樹進行操作來替換原本的程式碼。詳細文章可以看這裡https://zhuanlan.zhihu.com/p/64346538;
remax這裡是利用macro來進行一些巨集的替換,比如useAppEvent和usePageEvent等,替換為從remax/runtime中進行引入
import { createMacro } from 'babel-plugin-macros'; import createHostComponentMacro from './createHostComponent'; import requirePluginComponentMacro from './requirePluginComponent'; import requirePluginMacro from './requirePlugin'; import usePageEventMacro from './usePageEvent'; import useAppEventMacro from './useAppEvent'; function remax({ references,state }: { references: { [name: string]: NodePath[] }; state: any }) { references.createHostComponent?.forEach(path => createHostComponentMacro(path,state)); references.requirePluginComponent?.forEach(path => requirePluginComponentMacro(path,state)); references.requirePlugin?.forEach(path => requirePluginMacro(path)); const importer = slash(state.file.opts.filename); Store.appEvents.delete(importer); Store.pageEvents.delete(importer); references.useAppEvent?.forEach(path => useAppEventMacro(path,state)); references.usePageEvent?.forEach(path => usePageEventMacro(path,state)); } export declare function createHostComponent<P = any>( name: string,props: Array<string | [string,string]> ): React.ComponentType<P>; export declare function requirePluginComponent<P = any>(pluginName: string): React.ComponentType<P>; export declare function requirePlugin<P = any>(pluginName: string): P; export declare function usePageEvent(eventName: PageEventName,callback: (...params: any[]) => any): void; export declare function useAppEvent(eventName: AppEventName,callback: (...params: any[]) => any): void; export default createMacro(remax);
import * as t from '@babel/types';
import { slash } from '@remax/shared';
import { NodePath } from '@babel/traverse';
import Store from '@remax/build-store';
import insertImportDeclaration from './utils/insertImportDeclaration';
const PACKAGE_NAME = '@remax/runtime';
const FUNCTION_NAME = 'useAppEvent';
function getArguments(callExpression: NodePath<t.CallExpression>,importer: string) {
const args = callExpression.node.arguments;
const eventName = args[0] as t.StringLiteral;
const callback = args[1];
Store.appEvents.set(importer,Store.appEvents.get(importer)?.add(eventName.value) ?? new Set([event程式設計客棧Name.value]));
return [eventName,callback];
}
export default function useAppEvent(path: NodePath,state: any) {
const program = state.file.path;
const importer = slash(state.file.opts.filename);
const functionName = insertImportDeclaration(program,FUNCTION_NAME,PACKAGE_NAME);
const callExpression = path.findParent(p => t.isCallExpression(p)) as NodePath<t.CallExpression>;
const [eventName,callback] = getArguments(callExpression,importer);
callExpression.replaceWith(t.callExpression(t.identifier(functionName),[eventName,callback]));
}
個人感覺這個設計有些過於複雜,可能跟remax的設計有關,在remax/runtime中,useAppEvent實際從remax-framework-shared中匯出;
不過也倒是讓我學到了一種對程式碼修改的處理方式。
4、remax-cli remax的腳手架,整個remax工程,生成到小程式的編譯流程也是在這裡處理。
先來看一下一個作為Page的React檔案是如何與小程式的原生Page構造器關聯起來的。
假設原先頁面程式碼是這個樣子,
import * as React from 'react';
import { View,Text,Image } from 'remax/wechat';
import styles from './index.css';
export default () => {
return (
<View className={styles.app}>
<View className={styles.header}>
<Image
src="https://gw.alipayobjects.com/mdn/rms_b5fcc5/afts/img/A*OGyZSI087zkAAAAAAAAAAABkARQnAQ"
className={styles.logo}
alt="logo"
/>
<View className={styles.text}>
編輯 <Text className={styles.path}>src/pages/index/index.js</Text>開始
程式設計客棧</View>
</View>
</View>
);
};
這部分處理在remax-cli/src/build/entries/PageEntries.ts程式碼中,可以看到這裡是對原始碼進行了修改,引入了runtime中的createPageConfig函式來對齊React元件與小程式原生Page需要的屬性,同時呼叫原生的Page構造器來例項化頁面。
import * as path from 'path'; import VirtualEntry from './VirtualEntry'; export default class PageEntry extends VirtualEntry { outputSource() { return ` import { createPageConfig } from '@remax/runtime'; import Entry from './${path.basename(this.filename)}'; Page(createPageConfig(Entry,'${this.name}')); `; } }
createPageConfig來負責將React元件掛載到remax自定義的渲染容器中,同時對小程式Page的各個生命週期與remax提供的各種hook進行關聯
export default function createPageConfig(Page: React.ComponentType<any>,name: string) { const app = getApp() as any; const config: any = { data: { root: { children: [],},modalRoot: { children: [],wrapperRef: React.createRef<any>(),lifecycleCallback: {},onLoad(this: any,query: any) { const PageWrapper = createPageWrapper(Page,name); this.pageId = generatePageId(); this.lifecycleCallback = {}; this.data =程式設計客棧 { // Page中定義的data實際是remax在記憶體中生成的一顆映象樹 root: { children: [],modalRoot: { children: [],}; this.query = query; // 生成自定義渲染器需要定義的容器 this.container = new Container(this,'root'); this.modalContainer = new Container(this,'modalRoot'); // 這裡生成頁面級別的React元件 const pageElement = React.createElement(PageWrapper,{ page: this,query,modalContainer: this.modalContainer,ref: this.wrapperRef,}); if (app && app._mount) { this.element = createPortal(pageElement,this.container,this.pageId); app._mount(this); } else { // 呼叫自定義渲染器進行渲染 this.element = render(pageElement,this.container); } // 呼叫生命週期中的鉤子函式 return this.callLifecycle(Lifecycle.load,query); },onUnload(this: any) { this.callLifecycle(Lifecycle.unload); this.unloaded = true; this.container.clearUpdate(); app._unmount(this); },
Container是按照React自定義渲染規範定義的根容器,最終是在applyUpdate方法中呼叫小程式原生的setData方法來更新渲染檢視
applyUpdate() { if (this.stopUpdate || this.updateQueue.length === 0) { return; } const startTime = new Date().getTime(); if (typeof this.context.$spliceData === 'function') { let $batchedUpdates = (callback: () => void) => { callback(); }; if (typeof this.context.$batchedUpdates === 'function') { $batchedUpdates = this.context.$batchedUpdates; } $batchedUpdates(() => { this.updateQueue.map((update,index) => { let callback = undefined; if (index + 1 === this.updateQueue.length) { callback = () => { nativeEffector.run(); /* istanbul ignore next */ if (RuntimeOptions.get('debug')) { console.log(`setData => 回撥時間:${new Date().getTime() - startTime}ms`); } }; } if (update.type === 'splice') { this.context.$spliceData( { [this.normalizeUpdatePath([...update.path,'children'])]: [ update.start,update.deleteCount,...update.items,],callback ); } if (update.type === 'set') { this.context.setData( { [this.normalizeUpdatePath([...update.path,update.name])]: update.value,callback ); } }); }); this.updateQueue = []; return; } const updatePayload = this.updateQueue.reduce<{ [key: string]: any }>((acc,update) => { if (update.node.isDeleted()) { return acc; } if (update.type === 'splice') { acc[this.normalizeUpdatePath([...update.path,'nodes',update.id.toString()])] = update.items[0] || null; if (update.children) { acc[this.normalizeUpdatePath([...update.path,'children'])] = (update.children || []).map(c => c.id); } } else { acc[this.normalizeUpdatePath([...update.path,update.name])] = update.value; } return acc; },{}); // 更新渲染檢視 this.context.setData(updatePayload,() => { nativeEffector.run(); /* istanbul ignore next */ if (RuntimeOptions.get('debug')) { console.log(`setData => 回撥時間:${new Date().getTime() - startTime}ms`,updatePayload); } }); this.updateQueue = []; }
而對於容器的更新是在render檔案中的render方法進行的,
function getPublicRootInstance(container: ReactReconciler.FiberRoot) {
const containerFiber = container.current;
if (!containerFiber.child) {
return null;
}
return containerFiber.child.stateNode;
}
export default function render(rootElement: React.ReactElement | null,container: Container | AppContainer) {
// Create a root Contain程式設計客棧er if it doesnt exist
if (!container._rootContainer) {
container._rootContainer = ReactReconcilerInst.createContainer(container,false,false);
}
ReactReconcilerInst.updateContainer(rootElement,container._rootContainer,null,() => {
// ignore
});
return getPublicRootInstance(container._rootContainer);
}
另外這裡渲染的元件,其實也是經過了createPageWrapper包裝了一層,主要是為了處理一些forward-ref相關操作。
現在已經把頁面級別的React元件與小程式原生Page關聯起來了。
對於Component的處理與這個類似,可以看remax-cli/src/build/entries/ComponentEntry.ts檔案
import * as path from 'path'; import VirtualEntry from './VirtualEntry'; export default class ComponentEntry extends VirtualEntry { outputSource() { return ` import { createComponentConfig } from '@remax/runtime'; import Entry from './${path.basename(this.filename)}'; Component(createComponentConfig(Entry)); `; } }
那麼對於普通的元件,remax會把他們編譯稱為自定義元件,小程式的自定義元件是由json wxml wxss js組成,由React元件到這些檔案的處理過程在remax-cli/src/build/webpack/plugins/ComponentAsset中處理,生成wxml、wxss和js檔案
export default class ComponentAssetPlugin { builder: Builder; cache: SourceCache = new SourceCache(); constructor(builder: Builder) { this.builder = builder; } apply(compiler: Compiler) { compiler.hooks.emit.tapAsync(PLUGIN_NAME,async (compilation,callback) => { const { options,api } = this.builder; const meta = api.getMeta(); const { entries } = this.builder.entryCollection; await Promise.all( Array.from(entries.values()).map(async component => { if (!(component instanceof ComponentEntry)) { return Promise.resolve(); } const chunk = compilation.chunks.find(c => { return c.name === component.name; }); const modules = [...getModules(chunk),component.filename]; let templatePromise; if (options.turboRenders) { // turbo page templatePromise = createTurboTemplate(this.builder.api,options,component,modules,meta,compilation); } else { templatePromise = createTemplate(component,compilation,this.cache); } await Promise.all([ await templatePromise,await createManifest(this.builder,this.cache),]); }) ); callback(); }); } }
而Page的一系列檔案在remax-cli/src/build/webpack/plugins/PageAsset中進行處理,同時在createMainifest中會分析Page與自定義元件之間的依賴關係,自動生成usingComponents的關聯關係。
到此這篇關於採用React編寫小程式的Remax框架的編譯流程解析(推薦)的文章就介紹到這了,更多相關React編寫小程式內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!