在項目中,咱們用到了Taro3進行跨端開發,在這裏分享下Taro3的一些跨端跨框架原理,也是但願能幫助本身更好的去理解Taro背後的事情,也能加速定位問題。此文章也是起到一個拋磚引玉的效果,讓本身理解的更加深刻一點。css
過去的總體架構,它分爲兩個部分,第⼀部分是編譯時,第⼆部分是運⾏時。編譯時會先對⽤戶的 React 代碼進⾏編譯,轉換成各個端上的⼩程序均可以運⾏的代碼,而後再在各個⼩程序端上⾯都配上⼀個對應的運⾏時框架進⾏適配,最終讓這份代碼運⾏在各個⼩程序端上⾯。html
編譯時是使用 babel-parser 將 Taro 代碼解析成抽象語法樹,而後經過 babel-types 對抽象語法樹進行一系列修改、轉換操做,最後再經過 babel-generate 生成對應的目標代碼。前端
這樣的實現過程有三⼤缺點:node
再看⼀下運⾏時的缺陷。對於每一個⼩程序平臺,都會提供對應的⼀份運⾏時框架進⾏適配。當修改⼀些 Bug 或者新增⼀些特性的時候,須要同時去修改多份運⾏時框架。react
總的來講,以前的Taro3.0以前有如下問題:webpack
Taro 3 則能夠大體理解爲解釋型架構(相對於 Taro 1/2 而言),主要經過在小程序端模擬實現 DOM、BOM API 來讓前端框架直接運行在小程序環境中,從而達到小程序和 H5 統一的目的,而對於生命週期、組件庫、API、路由等差別,依然能夠經過定義統一標準,各端負責各自實現的方式來進行抹平。而正由於 Taro 3 的原理,在 Taro 3 中同時支持 React、Vue 等框架,甚至還支持了 jQuery,還能支持讓開發者自定義地去拓展其餘框架的支持,好比 Angular,Taro 3 總體架構以下:git
Taro 3 以後 ⼩程序端的總體架構。⾸先是⽤戶的 React 或 Vue 的代碼會經過 CLI 進⾏ Webpack 打包,其次在運⾏時會提供 React 和 Vue 對應的適配器進⾏適配,而後調⽤Taro提供的 DOM 和 BOM API, 最後把整個程序渲染到全部的⼩程序端上⾯。github
React 有點特殊,由於 React-DOM
包含大量瀏覽器兼容類的代碼,致使包太大,而這部分代碼是不須要的,所以作了一些定製和優化。web
在 React 16+ ,React 的架構以下:算法
最上層是 React 的核心部分 react-core
,中間是 react-reconciler
,其的職責是維護 VirtualDOM
樹,內部實現了 Diff/Fiber
算法,決定何時更新、以及要更新什麼。
而 Renderer
負責具體平臺的渲染工做,它會提供宿主組件、處理事件等等。例如 React-DOM
就是一個渲染器,負責 DOM 節點的渲染和 DOM 事件處理。
Taro實現了taro-react 包,用來鏈接 react-reconciler
和 taro-runtime
的 BOM/DOM API。是基於 react-reconciler
的小程序專用 React 渲染器,鏈接 @tarojs/runtime
的DOM 實例,至關於小程序版的react-dom,暴露的 API 也和react-dom 保持一致。
建立一個自定義渲染器只需兩步:具體的實現主要分爲兩步:
第一步: 實現宿主配置( 實現 **react-reconciler**
的 **hostConfig**
**配置)**這是react-reconciler
要求宿主提供的一些適配器方法和配置項。這些配置項定義瞭如何建立節點實例、構建節點樹、提交和更新等操做。即在 hostConfig
的方法中調用對應的 Taro BOM/DOM 的 API。
const Reconciler = require('react-reconciler');
const HostConfig = {
// ... 實現適配器方法和配置項
};
# @tarojs/react reconciler.ts
/* eslint-disable @typescript-eslint/indent */
import Reconciler, { HostConfig } from 'react-reconciler'
import * as scheduler from 'scheduler'
import { TaroElement, TaroText, document } from '@tarojs/runtime'
import { noop, EMPTY_ARR } from '@tarojs/shared'
import { Props, updateProps } from './props'
const {
unstable_scheduleCallback: scheduleDeferredCallback,
unstable_cancelCallback: cancelDeferredCallback,
unstable_now: now
} = scheduler
function returnFalse () {
return false
}
const hostConfig: HostConfig<
string, // Type
Props, // Props
TaroElement, // Container
TaroElement, // Instance
TaroText, // TextInstance
TaroElement, // HydratableInstance
TaroElement, // PublicInstance
Record<string, any>, // HostContext
string[], // UpdatePayload
unknown, // ChildSet
unknown, // TimeoutHandle
unknown // NoTimeout
> & {
hideInstance (instance: TaroElement): void
unhideInstance (instance: TaroElement, props): void
} = {
createInstance (type) {
return document.createElement(type)
},
createTextInstance (text) {
return document.createTextNode(text)
},
getPublicInstance (inst: TaroElement) {
return inst
},
getRootHostContext () {
return {}
},
getChildHostContext () {
return {}
},
appendChild (parent, child) {
parent.appendChild(child)
},
appendInitialChild (parent, child) {
parent.appendChild(child)
},
appendChildToContainer (parent, child) {
parent.appendChild(child)
},
removeChild (parent, child) {
parent.removeChild(child)
},
removeChildFromContainer (parent, child) {
parent.removeChild(child)
},
insertBefore (parent, child, refChild) {
parent.insertBefore(child, refChild)
},
insertInContainerBefore (parent, child, refChild) {
parent.insertBefore(child, refChild)
},
commitTextUpdate (textInst, _, newText) {
textInst.nodeValue = newText
},
finalizeInitialChildren (dom, _, props) {
updateProps(dom, {}, props)
return false
},
prepareUpdate () {
return EMPTY_ARR
},
commitUpdate (dom, _payload, _type, oldProps, newProps) {
updateProps(dom, oldProps, newProps)
},
hideInstance (instance) {
const style = instance.style
style.setProperty('display', 'none')
},
unhideInstance (instance, props) {
const styleProp = props.style
let display = styleProp?.hasOwnProperty('display') ? styleProp.display : null
display = display == null || typeof display === 'boolean' || display === '' ? '' : ('' + display).trim()
// eslint-disable-next-line dot-notation
instance.style['display'] = display
},
shouldSetTextContent: returnFalse,
shouldDeprioritizeSubtree: returnFalse,
prepareForCommit: noop,
resetAfterCommit: noop,
commitMount: noop,
now,
scheduleDeferredCallback,
cancelDeferredCallback,
clearTimeout: clearTimeout,
setTimeout: setTimeout,
noTimeout: -1,
supportsMutation: true,
supportsPersistence: false,
isPrimaryRenderer: true,
supportsHydration: false
}
export const TaroReconciler = Reconciler(hostConfig)
複製代碼
第二步:實現渲染函數,相似於ReactDOM.render() 方法。能夠當作是建立 Taro DOM Tree
容器的方法。
// 建立Reconciler實例, 並將HostConfig傳遞給Reconciler
const MyRenderer = Reconciler(HostConfig);
/** * 假設和ReactDOM同樣,接收三個參數 * render(<MyComponent />, container, () => console.log('rendered')) */
export function render(element, container, callback) {
// 建立根容器
if (!container._rootContainer) {
container._rootContainer = ReactReconcilerInst.createContainer(container, false);
}
// 更新根容器
return ReactReconcilerInst.updateContainer(element, container._rootContainer, null, callback);
}
複製代碼
通過上面的步驟,React 代碼實際上就能夠在小程序的運行時正常運行了,而且會生成 Taro DOM Tree
。那麼偌大的 Taro DOM Tree 怎樣更新到頁面呢?
由於⼩程序並無提供動態建立節點的能⼒,須要考慮如何使⽤相對靜態的 wxml 來渲染相對動態的 Taro DOM 樹。Taro使⽤了模板拼接的⽅式,根據運⾏時提供的 DOM 樹數據結構,各 templates 遞歸地 相互引⽤,最終能夠渲染出對應的動態 DOM 樹。
首先,將小程序的全部組件挨個進行模版化處理,從而獲得小程序組件對應的模版。以下圖就是小程序的 view 組件模版通過模版化處理後的樣子。⾸先須要在 template ⾥⾯寫⼀個 view,把它全部的屬性所有列出來(把全部的屬性都列出來是由於⼩程序⾥⾯不能去動態地添加屬性)。
接下來是遍歷渲染全部⼦節點,基於組件的 template,動態 「遞歸」 渲染整棵樹。
具體流程爲先去遍歷 Taro DOM Tree
根節點的子元素,再根據每一個子元素的類型選擇對應的模板來渲染子元素,而後在每一個模板中咱們又會去遍歷當前元素的子元素,以此把整個節點樹遞歸遍歷出來。
Taro 這邊遵循的是以微信小程序爲主,其餘小程序爲輔的組件與 API 規範。 但瀏覽器並無小程序規範的組件與 API 可供使用,咱們不能在瀏覽器上使用小程序的 view
組件和 getSystemInfo
API。所以Taro在 H5 端實現一套基於小程序規範的組件庫和 API 庫。
再來看⼀下 H5 端的架構,一樣的也是須要把⽤戶的 React 或者 Vue 代碼經過 Webpack 進⾏打包。而後在運⾏時作了三件事情:第⼀件事情是實現了⼀個組件庫,組件庫須要同時給到 React 、Vue 甚⾄更加多的⼀些框架去使⽤,Taro使⽤了 Stencil 去實現了⼀個基於 WebComponents 且遵循微信⼩程序規範的組件庫,第⼆、三件事是實現了⼀個⼩程序規範的 API 和路由機制,最終就能夠把整個程序給運⾏在瀏覽器上⾯。下面,咱們主要關注實現組件庫。
最早容易想到的是使用 Vue 再開發一套組件庫,這樣最爲穩妥,工做量也沒有特別大。
但考慮到如下兩點,官方遂放棄了此思路:
那麼是否存在着一種方案,使得只用一份代碼構建的組件庫能兼容全部的 web 開發框架呢?
Taro的選擇是 Web Components。
Web Components 由一系列的技術規範所組成,它讓開發者能夠開發出瀏覽器原生支持的組件。容許你建立可重用的定製元素(它們的功能封裝在你的代碼以外)而且在你的web應用中使用它們。
Web Components— 它由三項主要技術組成,它們能夠一塊兒使用來建立封裝功能的定製元素,能夠在你喜歡的任何地方重用,沒必要擔憂代碼衝突。
Custom elements(自定義元素):一組JavaScript API,容許您定義custom elements及其行爲,而後能夠在您的用戶界面中按照須要使用它們。簡單來講,就是讓開發者能夠自定義帶有特定行爲的 HTML 標籤。
Shadow DOM(影子DOM):一組JavaScript API,用於將封裝的「影子」DOM樹附加到元素(與主文檔DOM分開呈現)並控制其關聯的功能。經過這種方式,您能夠保持元素的功能私有,這樣它們就能夠被腳本化和樣式化,而不用擔憂與文檔的其餘部分發生衝突。簡單來講,就是對標籤內的結構和樣式進行一層包裝。
HTML templates(HTML模板): <template>
和<slot>
元素使您能夠編寫不在呈現頁面中顯示的標記模板。而後它們能夠做爲自定義元素結構的基礎被屢次重用。
實現web component的基本方法一般以下所示:
<template> 和 <slot>
定義一個HTML模板。再次使用常規DOM方法克隆模板並將其附加到您的shadow DOM中。定義模板:
<template id="template">
<h1>Hello World!</h1>
</template>
複製代碼
構造 Custom Element:
class App extends HTMLElement {
constructor () {
super(...arguments)
// 開啓 Shadow DOM
const shadowRoot = this.attachShadow({ mode: 'open' })
// 複用 <template> 定義好的結構
const template = document.querySelector('#template')
const node = template.content.cloneNode(true)
shadowRoot.appendChild(node)
}
}
window.customElements.define('my-app', App)
複製代碼
使用:
<my-app></my-app>
複製代碼
使用原生語法去編寫 Web Components 至關繁瑣,所以須要一個框架幫助咱們提升開發效率和開發體驗。業界已經有不少成熟的 Web Components 框架,Taro選擇的是Stencil,Stencil 是一個能夠生成 Web Components 的編譯器。它糅合了業界前端框架的一些優秀概念,如支持 Typescript、JSX、虛擬 DOM 等。
建立 Stencil Component:
import { Component, Prop, State, h } from '@stencil/core'
@Component({
tag: 'my-component'
})
export class MyComponent {
@Prop() first = ''
@State() last = 'JS'
componentDidLoad () {
console.log('load')
}
render () {
return (
<div> Hello, my name is {this.first} {this.last} </div>
)
}
}
複製代碼
使用組件:
<my-component first='Taro' />
複製代碼
Custom Elements Everywhere 上羅列出業界前端框架對 Web Components 的兼容問題及相關 issues。在React文檔中,也略微提到過在在 React 中使用 Web Components的注意事項 zh-hans.reactjs.org/docs/web-co…
在Custom Elements Everywhere 上能夠看到,React 對 Web Components 的兼容問題。
翻譯過來,就是說。
setAttribute
的形式給 Web Components 傳遞參數。當參數爲原始類型時是能夠運行的,可是若是參數爲對象或數組時,因爲 HTML 元素的 attribute 值只能爲字符串或 null,最終給 WebComponents 設置的 attribute 會是 attr="[object Object]"
。attribute和property的區別:stackoverflow.com/questions/6…
實際上,這個高階組件的實現是根據開源庫reactify-wc修改的一個版本,reactify-wc是一個銜接 WebComponent 和 React 的庫,目的是爲了在React 中可以使用 WebComponent。這個修改的庫就是爲了解決上述所說的問題。
Taro的處理,採用 DOM Property 的方法傳參。把 Web Components 包裝一層高階組件,把高階組件上的 props 設置爲 Web Components 的 property。
const reactifyWebComponent = WC => {
return class Index extends React.Component {
ref = React.createRef()
update (prevProps) {
this.clearEventHandlers()
if (!this.ref.current) return
Object.keys(prevProps || {}).forEach((key) => {
if (key !== 'children' && key !== 'key' && !(key in this.props)) {
updateProp(this, WC, key, prevProps, this.props)
}
})
Object.keys(this.props).forEach((key) => {
updateProp(this, WC, key, prevProps, this.props)
})
}
componentDidUpdate () {
this.update()
}
componentDidMount () {
this.update()
}
render () {
const { children, dangerouslySetInnerHTML } = this.props
return React.createElement(WC, {
ref: this.ref,
dangerouslySetInnerHTML
}, children)
}
複製代碼
由於 React 有一套本身實現的合成事件系統,因此它不能監聽到 Web Components 發出的自定義事件。如下 Web Component 的 onLongPress 回調不會被觸發:
<my-view onLongPress={onLongPress}>view</my-view>
複製代碼
經過 ref 取得 Web Component 元素,手動 addEventListener 綁定事件。改造上述的高階組件:
const reactifyWebComponent = WC => {
return class Index extends React.Component {
ref = React.createRef()
eventHandlers = []
update () {
this.clearEventHandlers()
Object.entries(this.props).forEach(([prop, val]) => {
if (typeof val === 'function' && prop.match(/^on[A-Z]/)) {
const event = prop.substr(2).toLowerCase()
this.eventHandlers.push([event, val])
return this.ref.current.addEventListener(event, val)
}
...
})
}
clearEventHandlers () {
this.eventHandlers.forEach(([event, handler]) => {
this.ref.current.removeEventListener(event, handler)
})
this.eventHandlers = []
}
componentWillUnmount () {
this.clearEventHandlers()
}
...
}
}
複製代碼
爲了解決 Props 和 Events 的問題,引入了高階組件。那麼當開發者向高階組件傳入 ref 時,獲取到的實際上是高階組件,但咱們但願開發者能獲取到對應的 Web Component。
domRef 會獲取到 MyComponent
,而不是 <my-component></my-component>
<MyComponent ref={domRef} />
複製代碼
使用 forwardRef 傳遞 ref。改造上述的高階組件爲 forwardRef 形式:
const reactifyWebComponent = WC => {
class Index extends React.Component {
...
render () {
const { children, forwardRef } = this.props
return React.createElement(WC, {
ref: forwardRef
}, children)
}
}
return React.forwardRef((props, ref) => (
React.createElement(Index, { ...props, forwardRef: ref })
))
}
複製代碼
在 Stencil 裏咱們可使用 Host 組件爲 host element 添加類名。
import { Component, Host, h } from '@stencil/core';
@Component({
tag: 'todo-list'
})
export class TodoList {
render () {
return (
<Host class='todo-list'> <div>todo</div> </Host>
)
}
}
複製代碼
而後在使用 <todo-list>
元素時會展現咱們內置的類名 「todo-list」 和 Stencil 自動加入的類名 「hydrated」:
關於類名 「hydrated」:
Stencil 會爲全部 Web Components 加上 visibility: hidden;
的樣式。而後在各 Web Component 初始化完成後加入類名 「hydrated」,將 visibility
改成 inherit
。若是 「hydrated」 被抹除掉,Web Components 將不可見。
爲了避免要覆蓋 wc 中 host 內置的 class 和 stencil 加入的 class,對對內置 class 進行合併。
function getClassName (wc, prevProps, props) {
const classList = Array.from(wc.classList)
const oldClassNames = (prevProps.className || prevProps.class || '').split(' ')
let incomingClassNames = (props.className || props.class || '').split(' ')
let finalClassNames = []
classList.forEach(classname => {
if (incomingClassNames.indexOf(classname) > -1) {
finalClassNames.push(classname)
incomingClassNames = incomingClassNames.filter(name => name !== classname)
} else if (oldClassNames.indexOf(classname) === -1) {
finalClassNames.push(classname)
}
})
finalClassNames = [...finalClassNames, ...incomingClassNames]
return finalClassNames.join(' ')
}
複製代碼
到這裏,咱們的reactify-wc就打造好了。咱們不要忘了,Stencil是幫咱們寫web components的,reactify-wc 目的是爲了在React 中可以使用 WebComponent。以下包裝後,咱們就能直接在react裏面用View、Text等組件了
//packages/taro-components/h5
import reactifyWc from './utils/reactify-wc'
import ReactInput from './components/input'
export const View = reactifyWc('taro-view-core')
export const Icon = reactifyWc('taro-icon-core')
export const Progress = reactifyWc('taro-progress-core')
export const RichText = reactifyWc('taro-rich-text-core')
export const Text = reactifyWc('taro-text-core')
export const Button = reactifyWc('taro-button-core')
export const Checkbox = reactifyWc('taro-checkbox-core')
export const CheckboxGroup = reactifyWc('taro-checkbox-group-core')
export const Editor = reactifyWc('taro-editor-core')
export const Form = reactifyWc('taro-form-core')
export const Input = ReactInput
export const Label = reactifyWc('taro-label-core')
export const Picker = reactifyWc('taro-picker-core')
export const PickerView = reactifyWc('taro-picker-view-core')
export const PickerViewColumn = reactifyWc('taro-picker-view-column-core')
export const Radio = reactifyWc('taro-radio-core')
export const RadioGroup = reactifyWc('taro-radio-group-core')
export const Slider = reactifyWc('taro-slider-core')
export const Switch = reactifyWc('taro-switch-core')
export const CoverImage = reactifyWc('taro-cover-image-core')
export const Textarea = reactifyWc('taro-textarea-core')
export const CoverView = reactifyWc('taro-cover-view-core')
export const MovableArea = reactifyWc('taro-movable-area-core')
export const MovableView = reactifyWc('taro-movable-view-core')
export const ScrollView = reactifyWc('taro-scroll-view-core')
export const Swiper = reactifyWc('taro-swiper-core')
export const SwiperItem = reactifyWc('taro-swiper-item-core')
export const FunctionalPageNavigator = reactifyWc('taro-functional-page-navigator-core')
export const Navigator = reactifyWc('taro-navigator-core')
export const Audio = reactifyWc('taro-audio-core')
export const Camera = reactifyWc('taro-camera-core')
export const Image = reactifyWc('taro-image-core')
export const LivePlayer = reactifyWc('taro-live-player-core')
export const Video = reactifyWc('taro-video-core')
export const Map = reactifyWc('taro-map-core')
export const Canvas = reactifyWc('taro-canvas-core')
export const Ad = reactifyWc('taro-ad-core')
export const OfficialAccount = reactifyWc('taro-official-account-core')
export const OpenData = reactifyWc('taro-open-data-core')
export const WebView = reactifyWc('taro-web-view-core')
export const NavigationBar = reactifyWc('taro-navigation-bar-core')
export const Block = reactifyWc('taro-block-core')
export const CustomWrapper = reactifyWc('taro-custom-wrapper-core')
//packages/taro-components/src/components/view/view.tsx
//拿View組件舉個例子
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { Component, Prop, h, ComponentInterface, Host, Listen, State, Event, EventEmitter } from '@stencil/core'
import classNames from 'classnames'
@Component({
tag: 'taro-view-core',
styleUrl: './style/index.scss'
})
export class View implements ComponentInterface {
@Prop() hoverClass: string
@Prop() hoverStartTime = 50
@Prop() hoverStayTime = 400
@State() hover = false
@State() touch = false
@Event({
eventName: 'longpress'
}) onLongPress: EventEmitter
private timeoutEvent: NodeJS.Timeout
private startTime = 0
@Listen('touchstart')
onTouchStart () {
if (this.hoverClass) {
this.touch = true
setTimeout(() => {
if (this.touch) {
this.hover = true
}
}, this.hoverStartTime)
}
this.timeoutEvent = setTimeout(() => {
this.onLongPress.emit()
}, 350)
this.startTime = Date.now()
}
@Listen('touchmove')
onTouchMove () {
clearTimeout(this.timeoutEvent)
}
@Listen('touchend')
onTouchEnd () {
const spanTime = Date.now() - this.startTime
if (spanTime < 350) {
clearTimeout(this.timeoutEvent)
}
if (this.hoverClass) {
this.touch = false
setTimeout(() => {
if (!this.touch) {
this.hover = false
}
}, this.hoverStayTime)
}
}
render () {
const cls = classNames({
[`${this.hoverClass}`]: this.hover
})
return (
<Host class={cls}> <slot></slot> </Host>
)
}
}
複製代碼
至此,組件庫就實現好了。
Taro 3 部分使用的 NPM 包名及其具體做用。
NPM 包 | 描述 |
---|---|
babel-preset-taro | 給 Taro 項目使用的 babel preset |
@tarojs/taro | 暴露給應用開發者的 Taro 核心 API |
@tarojs/shared | Taro 內部使用的 utils |
@tarojs/api | 暴露給 @tarojs/taro 的全部端的公有 API |
@tarojs/taro-h5 | 暴露給 @tarojs/taro 的 H5 端 API |
@tarojs/router | Taro H5 路由 |
@tarojs/react | 基於 react-reconciler 的小程序專用 React 渲染器 |
@tarojs/cli | Taro 開發工具 |
@tarojs/extend | Taro 擴展,包含 jQuery API 等 |
@tarojs/helper | 內部給 CLI 和 runner 使用輔助方法集 |
@tarojs/service | Taro 插件化內核 |
@tarojs/taro-loader | 露給 @tarojs/mini-runner 和 @tarojs/webpack-runner 使用的 Webpack loader |
@tarojs/runner-utils | 暴露給 @tarojs/mini-runner 和 @tarojs/webpack-runner 的公用工具函數 |
@tarojs/webpack-runner | Taro H5 端 Webpack 打包編譯工具 |
@tarojs/mini-runner | Taro 小程序 端 Webpack 打包編譯工具 |
@tarojs/components | Taro 標準組件庫,H5 版 |
@tarojs/taroize | Taro 小程序反向編譯器 |
@tarojs/with-weapp | 反向轉換的運行時適配器 |
eslint-config-taro | Taro ESLint 規則 |
eslint-plugin-taro | Taro ESLint 插件 |
Taro 3重構是爲了解決架構問題,還有提供多框架的⽀持。從以前的重編譯時,到如今的重運行時。
同等條件下,編譯時作的工做越多,也就意味着運行時作的工做越少,性能會更好。從長遠來看,計算機硬件的性能愈來愈冗餘,若是在犧牲一點能夠容忍的性能的狀況下換來整個框架更大的靈活性和更好的適配性,而且可以極大的提高開發體驗。