采用React編寫小程序的Remax框架的編譯流程解析(推薦)
Remax是螞蟻開源的一個(gè)用React來開發(fā)小程序的框架,采用運(yùn)行時(shí)無語法限制的方案。整體研究下來主要分為三大部分:運(yùn)行時(shí)原理、模板渲染原理、編譯流程;看了下現(xiàn)有大部分文章主要集中在Reamx的運(yùn)行時(shí)和模板渲染原理上,而對(duì)整個(gè)React代碼編譯為小程序的流程介紹目前還沒有看到,本文即是來補(bǔ)充這個(gè)空白。
關(guān)于模板渲染原理看這篇文章:http://www.dbjr.com.cn/article/132635.htm
關(guān)于remax運(yùn)行時(shí)原理看這篇文章:http://www.dbjr.com.cn/article/210293.htm
關(guān)于React自定義渲染器看這篇文章:http://www.dbjr.com.cn/article/198425.htm
Remax的基本結(jié)構(gòu):
1、remax-runtime 運(yùn)行時(shí),提供自定義渲染器、宿主組件的包裝、以及由React組件到小程序的App、Page、Component的配置生成器
// 自定義渲染器
export { default as render } from './render';
// 由app.js到小程序App構(gòu)造器的配置處理
export { default as createAppConfig } from './createAppConfig';
// 由React到小程序Page頁面構(gòu)造器的一系列適配處理
export { default as createPageConfig } from './createPageConfig';
// 由React組件到小程序自定義組件Component構(gòu)造器的一系列適配處理
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 小程序相關(guān)適配器
template模板相關(guān),與模板相關(guān)的處理原則及原理可以看這個(gè)http://www.dbjr.com.cn/article/145552.htm
templates // 與渲染相關(guān)的模板
src/api 適配與微信小程序相關(guān)的各種全局api,有的進(jìn)行了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相關(guān)配置內(nèi)容的適配處理
/** 頁面配置文件 */
// reference: https://developers.weixin.qq.com/miniprogram/dev/reference/configuration/page.html
export interface PageConfig {
/**
* 默認(rèn)值:#000000
* 導(dǎo)航欄背景顏色,如 #000000
*/
navigationBarBackgroundColor?: string;
/**
* 默認(rèn)值:white
* 導(dǎo)航欄標(biāo)題顏色,僅支持 black / white
*/
navigationBarTextStyle?: 'black' | 'white';
/** 全局配置文件 */
// reference: https://developers.weixin.qq.com/miniprogram/dev/reference/configuration/app.html
export interface AppConfig {
/**
* 頁面路徑列表
*/
pages: string[];
/**
* 全局的默認(rèn)窗口表現(xiàn)
*/
window?: {
/**
* 默認(rèn)值:#000000
* 導(dǎo)航欄背景顏色,如 #000000
*/
navigationBarBackgroundColor?: string;
/**
* 默認(rèn)值: white
* 導(dǎo)航欄標(biāo)題顏色,僅支持 black / white
*/
navigationBarTextStyle?: 'white' | 'black';
src/types/component.ts 微信內(nèi)置組件相關(guān)的公共屬性、事件等屬性適配
import * as React from 'react';
/** 微信內(nèi)置組件公共屬性 */
// reference: https://developers.weixin.qq.com/miniprogram/dev/framework/view/component.html
export interface BaseProps {
/** 自定義屬性: 組件上觸發(fā)的事件時(shí),會(huì)發(fā)送給事件處理函數(shù) */
readonly dataset?: DOMStringMap;
/** 組件的唯一標(biāo)示: 保持整個(gè)頁面唯一 */
id?: string;
/** 組件的樣式類: 在對(duì)應(yīng)的 WXSS 中定義的樣式類 */
className?: string;
/** 組件的內(nèi)聯(lián)樣式: 可以動(dòng)態(tài)設(shè)置的內(nèi)聯(lián)樣式 */
style?: React.CSSProperties;
/** 組件是否顯示: 所有組件默認(rèn)顯示 */
hidden?: boolean;
/** 動(dòng)畫對(duì)象: 由`wx.createAnimation`創(chuàng)建 */
animation?: Array<Record<string, any>>;
// reference: https://developers.weixin.qq.com/miniprogram/dev/framework/view/wxml/event.html
/** 點(diǎn)擊時(shí)觸發(fā) */
onTap?: (event: TouchEvent) => void;
/** 點(diǎn)擊時(shí)觸發(fā) */
onClick?: (event: TouchEvent) => void;
/** 手指觸摸動(dòng)作開始 */
onTouchStart?: (event: TouchEvent) => void;
src/hostComponents 針對(duì)微信小程序宿主組件的包裝和適配;node.ts是將小程序相關(guān)屬性適配到React的規(guī)范
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';
// 微信已不再維護(hù)
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的宏;所謂宏是在編譯時(shí)進(jìn)行字符串的靜態(tài)替換,而Javascript沒有編譯過程,babel實(shí)現(xiàn)宏的方式是在將代碼編譯為ast樹之后,對(duì)ast語法樹進(jìn)行操作來替換原本的代碼。詳細(xì)文章可以看這里https://zhuanlan.zhihu.com/p/64346538;
remax這里是利用macro來進(jìn)行一些宏的替換,比如useAppEvent和usePageEvent等,替換為從remax/runtime中進(jìn)行引入
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([eventName.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]));
}
個(gè)人感覺這個(gè)設(shè)計(jì)有些過于復(fù)雜,可能跟remax的設(shè)計(jì)有關(guān),在remax/runtime中,useAppEvent實(shí)際從remax-framework-shared中導(dǎo)出;
不過也倒是讓我學(xué)到了一種對(duì)代碼修改的處理方式。
4、remax-cli remax的腳手架,整個(gè)remax工程,生成到小程序的編譯流程也是在這里處理。
先來看一下一個(gè)作為Page的React文件是如何與小程序的原生Page構(gòu)造器關(guān)聯(lián)起來的。
假設(shè)原先頁面代碼是這個(gè)樣子,
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代碼中,可以看到這里是對(duì)源碼進(jìn)行了修改,引入了runtime中的createPageConfig函數(shù)來對(duì)齊React組件與小程序原生Page需要的屬性,同時(shí)調(diào)用原生的Page構(gòu)造器來實(shí)例化頁面。
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來負(fù)責(zé)將React組件掛載到remax自定義的渲染容器中,同時(shí)對(duì)小程序Page的各個(gè)生命周期與remax提供的各種hook進(jìn)行關(guān)聯(lián)
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實(shí)際是remax在內(nèi)存中生成的一顆鏡像樹
root: {
children: [],
},
modalRoot: {
children: [],
},
};
this.query = query;
// 生成自定義渲染器需要定義的容器
this.container = new Container(this, 'root');
this.modalContainer = new Container(this, 'modalRoot');
// 這里生成頁面級(jí)別的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 {
// 調(diào)用自定義渲染器進(jìn)行渲染
this.element = render(pageElement, this.container);
}
// 調(diào)用生命周期中的鉤子函數(shù)
return this.callLifecycle(Lifecycle.load, query);
},
onUnload(this: any) {
this.callLifecycle(Lifecycle.unload);
this.unloaded = true;
this.container.clearUpdate();
app._unmount(this);
},
Container是按照React自定義渲染規(guī)范定義的根容器,最終是在applyUpdate方法中調(diào)用小程序原生的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 => 回調(diào)時(shí)間:${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 => 回調(diào)時(shí)間:${new Date().getTime() - startTime}ms`, updatePayload);
}
});
this.updateQueue = [];
}
而對(duì)于容器的更新是在render文件中的render方法進(jìn)行的,
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 Container 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);
}
另外這里渲染的組件,其實(shí)也是經(jīng)過了createPageWrapper包裝了一層,主要是為了處理一些forward-ref相關(guān)操作。
現(xiàn)在已經(jīng)把頁面級(jí)別的React組件與小程序原生Page關(guān)聯(lián)起來了。
對(duì)于Component的處理與這個(gè)類似,可以看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));
`;
}
}
那么對(duì)于普通的組件,remax會(huì)把他們編譯稱為自定義組件,小程序的自定義組件是由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, options, meta, compilation, this.cache);
}
await Promise.all([
await templatePromise,
await createManifest(this.builder, component, compilation, this.cache),
]);
})
);
callback();
});
}
}
而Page的一系列文件在remax-cli/src/build/webpack/plugins/PageAsset中進(jìn)行處理,同時(shí)在createMainifest中會(huì)分析Page與自定義組件之間的依賴關(guān)系,自動(dòng)生成usingComponents的關(guān)聯(lián)關(guān)系。
到此這篇關(guān)于采用React編寫小程序的Remax框架的編譯流程解析(推薦)的文章就介紹到這了,更多相關(guān)React編寫小程序內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用React?SSR寫Demo一學(xué)就會(huì)
這篇文章主要為大家介紹了使用React?SSR寫Demo實(shí)現(xiàn)教程示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06
使用Jenkins部署React項(xiàng)目的方法步驟
這篇文章主要介紹了使用Jenkins部署React項(xiàng)目的方法步驟,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-03-03
React關(guān)于antd table中select的設(shè)值更新問題
這篇文章主要介紹了React關(guān)于antd table中select的設(shè)值更新問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03
react-native 封裝視頻播放器react-native-video的使用
本文主要介紹了react-native 封裝視頻播放器react-native-video的使用,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01

