基於目前React和Vue比較火,開發react-to-vue工具的目的是為了進一步提高組件的可復用用性,讓組件復用不僅僅局限在一個框架裡面
簡介對於react-to-vue工具,轉化的是基本的react component,而不是全部的react應用。而基本react component的定義更多是基於props和state來渲染的組件,其中也可以包括發請求。
本文先介紹兩個框架的組件共性和不兼容的地方,再介紹react-to-vue的使用和原理。在實際業務中,陸金所100多個的react基礎業務組件,react-to-vue可以轉化90%以上,變成vue組件。
// react
FrontendMagazine.propTypes = {
name: PropTypes.string
}
FrontendMagazine.defaultProps = {
name: 'FrontendMagazine'
}
// vue
{
name: 'frontend-magazine',
props: {
name: {
type: String,
default: 'FrontendMagazine'
}
}
}
2. 組件自有狀態框架說明React在初始化的時候,通過this.state = {xxx}來設置Vue通過data 返回函數來設置值,不同於react的state,vue是響應式3. 生命周期雖然生命周期名不一樣,但是差不多有對應的
// react
class FrontendMagazine {
clickme () {
// xxxx
}
}
// vue
{
name: 'frontend-magazine',
methods: {
clickme () {
// xxx
}
}
}
5. 組件錯誤捕獲框架說明ReactcomponentDidCatchVueerrorCaptured6. jsx語法react是基於jsx來寫的,對於vue來說,雖然在好多場景下,可以使用template來寫,但是vue也完全支持jsx語法的,對於本工具,也只是把react的jsx語法轉換成vue支持的jsx
兩個框架不兼容的地方react在最新版本裡面,有flagments的支持,允許根節點返回多個節點,目前沒有看到vue支持的,還有就是在設計react組件的時候,使用了高階,對於本工具,也是不支持的
react-to-vue工具安裝及使用# install
npm install -g react-to-vue
# usage
Usage: rtv [options] file(react component)
Options:
-V, --version output the version number
-o --output [string] the output file name
-t --ts it is a typescript component
-h, --help output usage information
# demo
rtv demo.js
原理步驟對於輸入的文件首先使用babylon來解析,生成ast
如果文件是typescript,會去掉相應的ts描述
對ast進行遍歷,首先提取propTypes和defaultProps
根據組件類型,處理函數組件和類組件
在類組件裡面,需要轉換生命周期,state等信息
最後根據提取到的信息拼接成vue組件,通過prettier-eslint來美化
轉化前後對比如果你的組件想要被大家開源使用,作者這裡有一個小提議,可以邊寫react組件,邊試著轉化成vue組件,如果轉化有問題,試著改代碼,儘可能跨框架支持,這樣你寫的組件肯定可以在react和vue項目中同時使用。
結尾項目地址: https://github.com/vicwang163/react-to-vue/, 歡迎各位大大來提bug,把項目越做越好