• React18组件一键转换Vue3组件


    需求来源

    博主最近一段时间其实是在自研React组件库的业务的,目前也有了大约二十几个组件,这里顺便先留一下组件库的地址哈~

    React-View-UI组件库线上链接:http://react-view-ui.com:92/#/
    github:https://github.com/fengxinhhh/React-View-UI-fs
    npm:https://www.npmjs.com/package/react-view-ui

    组件库文档:

    在这里插入图片描述
    在这里插入图片描述

    嗯,先卖个关子,然后回归主题,其实现在Vue也是很火的框架随着Vue3的诞生,博主其实最终目标是想整合一套React+一套Vue组件库在一起的,但是重写一遍React的组件很费工作量也不现实,因为我是单人开发,于是就萌生了写一个React组件转换Vue组件的工具。

    市场环境

    目前市场上也有这样的转换工具,但是局限性比较高,如React Class组件转换Vue组件,类组件其实在现在用的是很少的,随着React16.8的出现,hooks的到来,函数组件火热,让React的组件写的更加灵活舒适,因此只能选择自研一个转换工具。

    效果演示

    目前工具已经开发一天,只能实现一些基本的语法转换,后期也会更新工具研发流程,最后会有github,可以关注一下。

    目前的转换效果是这样的:
    在这里插入图片描述
    目前写了除基本模板以外,react的useEffect、useState转换 -> vue的ref、recative、setup、mounted、unmounted、watch。

    因此本文目的主要为了记录以及分享开发的过程和思路。

    转换

    转换的入口就在index.js -> transformOptions变量中,可以配置css为less/scss,配置入口源文件路径和出口路径,在终端执行node src/index即可转换。

    设计

    入口函数就在index.js的第26行:

    readFileFromLine(transformOptions.sourcePath, (res) => {
    
    }
    
    • 1
    • 2
    • 3

    将转换的配置传入函数,进行处理。readFileFromLine函数可以将我们输入的文件按行输出,变成一个数组,让我们一行一行进行判断处理。

    const fs = require('fs');
    const readline = require('readline');
    
    const readFileFromLine = (path, callback) => {
      var fRead = fs.createReadStream(path);
      var objReadline = readline.createInterface({
        input: fRead
      });
      var arr = new Array();
      objReadline.on('line', function (line) {
        arr.push(line);
      });
      objReadline.on('close', function () {
        callback(arr);
      });
    }
    
    module.exports = {
      readFileFromLine
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    这里传入了源文件的路径,并且返回了文件切割后的以行为元素的数组,并且准备了一些全局变量,用于模板的保存、导入依赖包的记录、栈的实例,这里栈主要用作记录任务优先级,举个例子吧,在useEffect中遇到了return()=>,原本在做对应vue mounted的模板处理,应在遇到return()=>之后去做vue unmounted的处理,这就是栈的需求,可以调度我们的任务分配,每行代码会去执行当前栈顶的任务。

    设计变量如下:

    const vueTemplateList = [];               //vue模板内容
    const vueScriptList = [];                 //vue script内容
    let fsContent = [];                       //react源文件
    let compileStack = new Stack();              //以栈顶值作为优先级最高的编译任务调度,1 -> 常规编译 ,2 -> 副作用函数编译中, 3 -> 模板编译中, 4 -> 引用数据类型状态编译中, 5 -> 组件销毁生命周期
    compileStack.unshift(1);
    let reactFileHasStateType = [];         //1为基本数据类型ref,2为引用数据类型reactive,3为mounted,4为watch,5为unmounted
    let allStateList = new Map();                  //所有状态的列表
    let resultFileTotalLine = 0;              //结果文件总行数
    let mountedContainer = "";              //mounted临时容器
    let unMountedContainer = "";            //unMounted临时容器
    let stateContainer = "";                  //复杂state临时容器
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    1. vueTemplateList用于保存模板代码段;
    2. vueScriptList用于保存逻辑代码段;
    3. fsContent用于接收入口函数处理后的代码片段(代码行为分割的数组);
    4. compileStack用于分配任务调度优先级,默认为1。1 -> 常规编译 ,2 -> 副作用函数编译中, 3 -> 模板编译中, 4 -> 引用数据类型状态编译中, 5 -> 组件销毁生命周期;
    5. allStateList记录所有的状态,以状态名:状态值为键值对形式保存在map中;
    6. resultFileTotalLine用于在最后记录输出文件的行数;
    7. mountedContainer用于存放在mounted处理时的代码保存容器(任务标识->2);
    8. unMountedContainer用于存放在unmounted处理时的代码保存容器(任务标识->5);
    9. stateContainer用于存放复杂状态的代码段,因为它由多行代码保存(任务标识->4);

    有了栈的任务分配,因此在每行代码做处理前,我们需要确定它的任务标识号是多少,从而进行处理,而在某个react关键词结束时,如useEffect —> ,[]),将任务栈栈顶弹出,转做新的任务,这就是栈的好处。

    接下来就是主体处理流程了,先看一下五个条件分支吧:

    处理(5个任务)

    comipleStack.peek() === 1时,是常规编译,这时会对当前行的代码进行判断,是否有react的一些关键词,如’return('开头应是template处理;'useEffect’应对应vue的mounted/watch处理。
    如果捕捉到了关键字,则comipleStack.peek()会改变,同时在下一行代码的处理时直接进行2/3/4/5的分支进行对应的编译;如果没有捕捉到关键字,则跳过。

    if (compileStack.peek() === 1) {               //常规编译,捕捉当前行是否为特殊编译
          if (lineItem === 'return(') {        //开始输出模板
            compileStack.unshift(3);
          }
          else if (lineItem.startsWith('const[') && lineItem.includes('useState')) {      //如果是状态声明
            const {
              returnCodeLine,
              returnAllStateList,
              returnCompileStack,
              returnReactFileHasStateType
            } = saveState(lineItem, allStateList, compileStack, reactFileHasStateType);
            vueScriptList.push(returnCodeLine);
            allStateList = returnAllStateList;
            compileStack = returnCompileStack;
            reactFileHasStateType = returnReactFileHasStateType;
          }
          else if (lineItem.startsWith('useEffect')) {             //副作用函数
            compileStack.unshift(2);
          }
          else {
            //被舍弃的,跳过循环,不做编译,一些特殊react专属语法,如export default function Index()/import './index.module.less';
          }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    comipleStack.peek() === 2时,是副作用函数编译,也就是useEffect转mounted/watch,在这分支中每一行只要捕捉到了’return()=>'则截取上段代码,作为mounted代码片段,并在return()=>之后进行unmounted代码片段的截取,在最后截取的时候,如果是"},[])",代表这是一个mounted函数;如果是
    “},[”,代表这是一个状态监听函数(vue watch),则切割出副作用状态,进行处理,编译模板。

    else if (compileStack.peek() === 2) {          //副作用函数编译中
          const saveCodeResult = saveCodeInUseEffect(allStateList, lineItem, compileStack)
          if (saveCodeResult.action === 'unmounted') {        //调度到unmounted
            compileStack = saveCodeResult.compileStack;
          } else {                        //仍然在执行mounted任务
            if (lineItem.startsWith('},[])')) {       //mounted结束,批量插入
              mountedContainer = '\nonMounted(() => {\n' + mountedContainer + '})\n';
              vueScriptList.push(mountedContainer);
              vueScriptList.push(unMountedContainer);
              mountedContainer = "";
              unMountedContainer = "";
              compileStack.shift();
              if (!reactFileHasStateType.includes(3)) {
                reactFileHasStateType.push(3);
              }
            } else if (lineItem.startsWith('},[')) {      //编译成watch函数,批量插入
              const params = lineItem.split('[')[1].split(']')[0].split(',');
              vueScriptList.push(formatWatchToVue(params, mountedContainer));
              if (!reactFileHasStateType.includes(4)) {
                reactFileHasStateType.push(4);
              }
              compileStack.shift();
            } else {
              mountedContainer += saveCodeResult;
            }
          }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    compileStack.peek() === 3代表模板编译,以"return(“作为开始(在compileStack.peek() === 1)中会捕获到,并改变,以结尾”)"作为模板编译结束,中间对className处理为class。
    这里博主功能还没有完善好,后期会做遍历渲染、条件渲染、vue语法糖的转换,这里仅做参考。

    else if (compileStack.peek() === 3) {             //模板编译中
          lineItem = lineItem.replace('className', 'class')
          if (lineItem.includes(')') && lineItem.replace(/\s*/g, "") === ')') {                 //模板输出结束
            compileStack.shift();
          }
          else if (lineItem.includes('{') && lineItem.includes('}')) {        //带状态的模板
            vueTemplateList.push(formatStateInTemplate(lineItem));
          } else {
            vueTemplateList.push(lineItem);
          }
        }
        else if (compileStack.peek() === 4) {         //复杂状态编译中
          if (lineItem.includes(')')) {         // 编译结束
            stateContainer += `\n${lineItem}`;
            vueScriptList.push(stateContainer);
            stateContainer = '';
            compileStack.shift();
          } else {
            stateContainer += `${lineItem}`;
          }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    compileStack.peek() === 4代表复杂状态编译,什么是复杂状态编译,比如有这样的状态声明:

    const [newList, setNewList] = useState({
        age: 20,
        hobby: '学习'
      });
    
    • 1
    • 2
    • 3
    • 4

    这样的状态并不在一行,因此要捕捉到从首行起"({“对应之后的”})",对复杂的状态进行存储,改变。

    else if (compileStack.peek() === 4) {         //复杂状态编译中
          if (lineItem.includes(')')) {         // 编译结束
            stateContainer += `\n${lineItem}`;
            vueScriptList.push(stateContainer);
            stateContainer = '';
            compileStack.shift();
          } else {
            stateContainer += `${lineItem}`;
          }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    对应的状态处理在这里:

    在这里插入图片描述

    对应的saveState方法在这里:

    const saveState = (lineItem, allStateList, compileStack, reactFileHasStateType) => {           //保存状态
      //处理useState hook
      const stateKey = lineItem.split('[')[1].split(',')[0];
      const stateVal = lineItem.split('useState(')[1].split(')')[0];        //状态值
      let returnCodeLine = '';
      if (!lineItem.includes(')')) {
        compileStack.unshift(4);
      }
      //判断state 类型,保存
      if (stateVal.startsWith('[') || stateVal.startsWith('{')) {
        returnCodeLine = `const ${stateKey}=reactive(${stateVal}${compileStack.peek() === 4 ? '' : ')'}`
        allStateList.set({ state: stateKey, stateAction: `set${formatUseStateAction(stateKey)}` }, 'reactive');
        if (!reactFileHasStateType.includes(2)) {
          reactFileHasStateType.push(2);
        }
      } else {
        returnCodeLine = `const ${stateKey}=ref(${stateVal})`;
        allStateList.set({ state: stateKey, stateAction: `set${formatUseStateAction(stateKey)}` }, 'ref');
        if (!reactFileHasStateType.includes(1)) {
          reactFileHasStateType.push(1);
        }
      }
      const returnAllStateList = allStateList;
      const returnCompileStack = compileStack;
      const returnReactFileHasStateType = reactFileHasStateType
      return {
        returnCodeLine,
        returnAllStateList,
        returnCompileStack,
        returnReactFileHasStateType
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    saveState中就写到了对复杂状态(多行)、简单状态(单行)的分别处理。

    compileStack.peek() === 5代表unmounted函数编译,也就是在compileStack.peek() === 2中再次捕捉到的编译处理,此时的优先级unmounted会更高,因为需要处理unmounted的代码,保存,因此任务优先级栈会是[5, 2, 1],当unmounted代码被保存后,则弹出栈顶,继续useEffect的处理。

    else if (compileStack.peek() === 5) {           //unmounted函数编译中
          if (lineItem.startsWith('}')) {         //可能unmounted结束了,需要先判断是否是块作用域
            const startIconNum = unMountedContainer.split('{').filter(item => item === '').length;
            const endIconNum = unMountedContainer.split('}').filter(item => item === '').length;
            if (startIconNum === endIconNum) {         //执行unmounted
              compileStack.shift();
              unMountedContainer = 'onUnmounted(() => {\n' + unMountedContainer + '})\n';
              if (!reactFileHasStateType.includes(5)) {
                reactFileHasStateType.push(5);
              }
            }
          } else {
            unMountedContainer += saveCodeInUnmounted(allStateList, lineItem, compileStack)
          }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    源码

    index.js(入口文件)

    const fs = require('fs');
    const path = require('path');
    const { readFileFromLine } = require('./write');
    const { Stack } = require('./stack');
    const { computeFileLines } = require('./_utils/computeFileLines')
    
    const { formatStateInTemplate, saveCodeInUseEffect, saveCodeInUnmounted, formatWatchToVue, saveState } = require('./compile');
    
    const transformOptions = {
      sourcePath: path.resolve(__dirname, 'sourceFile', 'index.jsx'),
      outputPath: path.resolve(__dirname, 'outputFile', 'index.vue'),
      styleType: 'less'
    }
    const vueTemplateList = [];               //vue模板内容
    const vueScriptList = [];                 //vue script内容
    let fsContent = [];                       //react源文件
    let compileStack = new Stack();              //以栈顶值作为优先级最高的编译任务调度,1 -> 常规编译 ,2 -> 副作用函数编译中, 3 -> 模板编译中, 4 -> 引用数据类型状态编译中, 5 -> 组件销毁生命周期
    compileStack.unshift(1);
    let reactFileHasStateType = [];         //1为基本数据类型ref,2为引用数据类型reactive,3为mounted,4为watch,5为unmounted
    let allStateList = new Map();                  //所有状态的列表
    let resultFileTotalLine = 0;              //结果文件总行数
    let mountedContainer = "";              //mounted临时容器
    let unMountedContainer = "";            //unMounted临时容器
    let stateContainer = "";                  //复杂state临时容器
    
    readFileFromLine(transformOptions.sourcePath, (res) => {
      fsContent = res;
      fsContent = fsContent.filter(line => line !== "");
      fsContent.forEach(lineItem => {
        if (compileStack.peek() !== 3) {
          lineItem = lineItem.replace(/\s*/g, "");
        }
        if (compileStack.peek() === 1) {               //常规编译,捕捉当前行是否为特殊编译
          if (lineItem === 'return(') {        //开始输出模板
            compileStack.unshift(3);
          }
          else if (lineItem.startsWith('const[') && lineItem.includes('useState')) {      //如果是状态声明
            const {
              returnCodeLine,
              returnAllStateList,
              returnCompileStack,
              returnReactFileHasStateType
            } = saveState(lineItem, allStateList, compileStack, reactFileHasStateType);
            vueScriptList.push(returnCodeLine);
            allStateList = returnAllStateList;
            compileStack = returnCompileStack;
            reactFileHasStateType = returnReactFileHasStateType;
          }
          else if (lineItem.startsWith('useEffect')) {             //副作用函数
            compileStack.unshift(2);
          }
          else {
            //被舍弃的,跳过循环,不做编译,一些特殊react专属语法,如export default function Index()/import './index.module.less';
          }
        }
        else if (compileStack.peek() === 2) {          //副作用函数编译中
          const saveCodeResult = saveCodeInUseEffect(allStateList, lineItem, compileStack)
          if (saveCodeResult.action === 'unmounted') {        //调度到unmounted
            compileStack = saveCodeResult.compileStack;
          } else {                        //仍然在执行mounted任务
            if (lineItem.startsWith('},[])')) {       //mounted结束,批量插入
              mountedContainer = '\nonMounted(() => {\n' + mountedContainer + '})\n';
              vueScriptList.push(mountedContainer);
              vueScriptList.push(unMountedContainer);
              mountedContainer = "";
              unMountedContainer = "";
              compileStack.shift();
              if (!reactFileHasStateType.includes(3)) {
                reactFileHasStateType.push(3);
              }
            } else if (lineItem.startsWith('},[')) {      //编译成watch函数,批量插入
              const params = lineItem.split('[')[1].split(']')[0].split(',');
              vueScriptList.push(formatWatchToVue(params, mountedContainer));
              if (!reactFileHasStateType.includes(4)) {
                reactFileHasStateType.push(4);
              }
              compileStack.shift();
            } else {
              mountedContainer += saveCodeResult;
            }
          }
        }
        else if (compileStack.peek() === 3) {             //模板编译中
          lineItem = lineItem.replace('className', 'class')
          if (lineItem.includes(')') && lineItem.replace(/\s*/g, "") === ')') {                 //模板输出结束
            compileStack.shift();
          }
          else if (lineItem.includes('{') && lineItem.includes('}')) {        //带状态的模板
            vueTemplateList.push(formatStateInTemplate(lineItem));
          } else {
            vueTemplateList.push(lineItem);
          }
        }
        else if (compileStack.peek() === 4) {         //复杂状态编译中
          if (lineItem.includes(')')) {         // 编译结束
            stateContainer += `\n${lineItem}`;
            vueScriptList.push(stateContainer);
            stateContainer = '';
            compileStack.shift();
          } else {
            stateContainer += `${lineItem}`;
          }
        }
        else if (compileStack.peek() === 5) {           //unmounted函数编译中
          if (lineItem.startsWith('}')) {         //可能unmounted结束了,需要先判断是否是块作用域
            const startIconNum = unMountedContainer.split('{').filter(item => item === '').length;
            const endIconNum = unMountedContainer.split('}').filter(item => item === '').length;
            if (startIconNum === endIconNum) {         //执行unmounted
              compileStack.shift();
              unMountedContainer = 'onUnmounted(() => {\n' + unMountedContainer + '})\n';
              if (!reactFileHasStateType.includes(5)) {
                reactFileHasStateType.push(5);
              }
            }
          } else {
            unMountedContainer += saveCodeInUnmounted(allStateList, lineItem, compileStack)
          }
        }
      })
    
      vueTemplateList.unshift('<template>');
      vueTemplateList.push('</template>\n');
      vueScriptList.unshift('<script setup>');
      vueScriptList.push('</script>\n');
    
      //处理import ..... from 'vue'  的导入配置
      if (reactFileHasStateType.length) {         //有状态
        let importVal = ''
        if (reactFileHasStateType.includes(1)) {
          importVal = 'ref';
        }
        if (reactFileHasStateType.includes(2)) {
          importVal += ',reactive';
        }
        if (reactFileHasStateType.includes(3)) {
          importVal += ',onMounted';
        }
        if (reactFileHasStateType.includes(4)) {
          importVal += ',watch';
        }
        if (reactFileHasStateType.includes(5)) {
          importVal += ',onUnmounted';
        }
        vueScriptList.splice(1, 0, `import{${importVal}}from'vue'`);
      }
    
      resultFileTotalLine = computeFileLines(vueTemplateList, vueScriptList);
    
      let resultFile = '';
      vueTemplateList.forEach(line => {
        resultFile += line + '\n';;
      })
      vueScriptList.forEach(line => {
        resultFile += line + '\n';
      })
      resultFile += `<style lang="${transformOptions.styleType}" scoped>\n`;
      readFileFromLine('./index.module.less', (res => {       //写入样式
        if (res) {
          res.forEach(line => {
            resultFile += line + '\n';
          })
          resultFile += '</style>';
          resultFileTotalLine += res.length + 3;
          //保存文件
          fs.writeFile(transformOptions.outputPath, resultFile, (err) => {
            if (!err) {
              console.log('转换完成,vue文件共有', resultFileTotalLine, '行代码!');
              return
            }
          })
        }
      }))
    });
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174

    compile.js(index.js中提供的工具函数,与index.js交互,处理代码段)

    const { formatUseStateAction } = require('./_utils/formatuseState')
    
    const formatStateInTemplate = (lineItem) => {         //编译模板中的{{state}}
      let startIndex = lineItem.indexOf('{');
      let endIndex = lineItem.indexOf('}');
      lineItem = lineItem.split('');
      lineItem.splice(startIndex + 1, 0, '{');
      lineItem.splice(endIndex + 2, 0, '}');
      lineItem = lineItem.join('');
      return lineItem;
    }
    
    const saveCodeInUseEffect = (allStateList, lineItem, compileStack) => {             //在useEffect中保存代码片段
      if (lineItem.includes('return()=>')) {             //组件销毁,把任务权先交给销毁
        compileStack.unshift(5);
        return { compileStack, action: 'unmounted' };
      }
      allStateList.forEach((stateType, key) => {
        if (lineItem.includes(key.stateAction)) {       //携带状态的特殊副作用函数语句
          let newState = lineItem.match(/\((.+?)\)/gi)[0].replace(/[(|)]/g, "");
          if (newState.includes(key.state)) {
            newState = newState.replace(key.state, `${key.state}.value`)
          }
          lineItem = `${key.state}${stateType === 'ref' ? '.value' : ''} = ${newState}`;
        }
      })
      return `${lineItem}\n`;
    }
    const saveCodeInUnmounted = (allStateList, lineItem, compileStack) => {       //在unmounted中保存代码片段
      allStateList.forEach((stateType, key) => {
        if (lineItem.includes(key.stateAction)) {       //携带状态的特殊副作用函数语句
          const newState = lineItem.match(/\((.+?)\)/gi)[0].replace(/[(|)]/g, "");
          lineItem = `${key.state}${stateType === 'ref' ? '.value' : ''} = ${newState}`;
        }
      })
    
      return `${lineItem}\n`;
    }
    const formatWatchToVue = (params, code) => {
      const returnCode = `watch([${params}],(${new Array(params.length).fill('').map((item, index) => {
        return `[${'oldValue' + index}, ${'newValue' + index}]`
      }
      )})=>{\n${code}})`;
      return returnCode;
    }
    
    const saveState = (lineItem, allStateList, compileStack, reactFileHasStateType) => {           //保存状态
      //处理useState hook
      const stateKey = lineItem.split('[')[1].split(',')[0];
      const stateVal = lineItem.split('useState(')[1].split(')')[0];        //状态值
      let returnCodeLine = '';
      if (!lineItem.includes(')')) {
        compileStack.unshift(4);
      }
      //判断state 类型,保存
      if (stateVal.startsWith('[') || stateVal.startsWith('{')) {
        returnCodeLine = `const ${stateKey}=reactive(${stateVal}${compileStack.peek() === 4 ? '' : ')'}`
        allStateList.set({ state: stateKey, stateAction: `set${formatUseStateAction(stateKey)}` }, 'reactive');
        if (!reactFileHasStateType.includes(2)) {
          reactFileHasStateType.push(2);
        }
      } else {
        returnCodeLine = `const ${stateKey}=ref(${stateVal})`;
        allStateList.set({ state: stateKey, stateAction: `set${formatUseStateAction(stateKey)}` }, 'ref');
        if (!reactFileHasStateType.includes(1)) {
          reactFileHasStateType.push(1);
        }
      }
      const returnAllStateList = allStateList;
      const returnCompileStack = compileStack;
      const returnReactFileHasStateType = reactFileHasStateType
      return {
        returnCodeLine,
        returnAllStateList,
        returnCompileStack,
        returnReactFileHasStateType
      }
    }
    
    module.exports = {
      formatStateInTemplate,
      saveCodeInUseEffect,
      saveCodeInUnmounted,
      formatWatchToVue,
      saveState
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86

    这里文中主要涉及到的源码就是这两个文件,具体的可以看一下github。

    总结

    React组件转换Vue组件的工具(react to vue)目前开工不久,博主在每一段大的变动时都会记录总结,也可以关注github,更新的会比较频繁。

    github地址:https://github.com/fengxinhhh/react-to-vue

    喜欢可以关注一下,有任何问题或者开发设计的意见也欢迎留言。

  • 相关阅读:
    java-net-php-python-jsp果蔬预约种植管理系统计算机毕业设计程序
    深析C语言的灵魂 -- 指针
    深度解读篇章:剖析构建互联网大厦的基石——TCP/IP协议全貌
    Golang 结构化日志包 log/slog 详解(四):分组、上下文和属性值类型
    多测师肖sir___接口自动化测试框架(python+request+unittest+ddt)
    VScode项目名变绿解决问题
    软文撰写技巧:中小企业品牌形象塑造新方法
    『期末复习』微处理器发展历程与微型计算机结构
    Spring Boot 2.x系列【19】功能篇之自定义Starter 启动器
    JAVA-----注释、字面量、关键字、制表符
  • 原文地址:https://blog.csdn.net/m0_46995864/article/details/125438078