Babel 将逗号表达式还原为多个语句

需求

为什么要将逗号表达式还原为多个语句 ?

代码样例(encode.js)

var a = 1, b = 2;
let c = 3;
const d = 4;
let e, f, g = function () { console.log('ggg'); };
g();

处理后代码(decode.js)

var a = 1;
var b = 2;
let c = 3;
const d = 4;
let e;
let f;

let g = function () {
  console.log('ggg');
};

g();

思路

在在线解析网站 ast explorer 观察 VariableDeclarationVariableDeclarator 区别,然后构造替换节点即可

编写 babel 插件

直接上完整插件代码

// decrypt.js
const fs = require('fs');
var util = require('util');
const parser = require('@babel/parser');
const traverse = require('@babel/traverse').default;
const types = require('@babel/types');
const generator = require('@babel/generator').default;

// 程序启动时间
var time_start = new Date().getTime()
// 读取文件
process.argv.length > 2 ? encode_file = process.argv[2] : encode_file = 'encode.js';
process.argv.length > 3 ? decode_file = process.argv[3] : decode_file = 'decode.js';

let jscode = fs.readFileSync(encode_file, { encoding: 'utf-8' });
console.log(util.format('Reading the file [%s] is complete.', encode_file))
// 转换为 ast 树
let ast = parser.parse(jscode);

const visitor =
{
  VariableDeclaration(path) {
    const { kind, declarations } = path.node;

    // 必须要加此处判断,不然会死循环,因为我们在下面的操作也生成了 VariableDeclaration
    if (declarations.length <= 1) {
      return;
    }

    let tmp_array = [];
    for (let variable_declarator of declarations) {
      tmp_array.push(types.VariableDeclaration(kind, [variable_declarator]));
    }

    path.replaceWithMultiple(tmp_array);
  }
}

//调用插件,处理待处理 js ast 树
traverse(ast, visitor);
console.log('AST traverse completed.')

// 生成处理后的 js
let { code } = generator(ast);
console.log('AST generator completed.')
fs.writeFile(decode_file, code, (err) => { });
console.log(util.format('The javascript code in [%s] has been processed.', encode_file))
console.log(util.format('The processing result has been saved to [%s].', decode_file))
// 程序结束时间
var time_end = new Date().getTime()
console.log(util.format('The program runs to completion, time-consuming: %s s', (time_end - time_start) / 1000))

推荐阅读

参考

Table of Contents