利用ast修改js,并保存硬盘

案例js文件

  1. 文件路径:src/router/a.js
  2. 文件内容:
export default {
  fixed: [],
  fluid: []
}

js解析器

  1. 使用@babel/core 把js 解析为jsonTree
	const babelPath = '@babel/core'
	const babel = require(babelPath);
	/**
	 * @code 字符串code
	 * @description 生成ast
	 */
	function generatingAst (code) {
	  const ast =  babel.parse(code);
	  return ast
	}
	// 读取js 文件
	const jsPath = 'src/router/a.js'
	fs.readFile(jsPath, 'utf8', function(err, data) {
	  if (err) {
	      console.error(err);
	      return;
	  } 
     const ast = generatingAst(data)
  });
  1. 循环ast
/**
 * @ast ast json
 * @description 循环ast对象,修改ast
 */
 // 添加ast循环包
const traversePath = '@babel/traverse'
const traverse = require(traversePath).default;
function estraverseAst (ast) {
  const templateAST = generatingTemplateAst('{a:1,()=>{}}');
  traverse(ast, {
    enter(path) {
      // 向 fixed 数组添加节点
      if (path.node.type === 'ObjectProperty' && path.node.key.name === 'fixed') {
        path.node.value.elements.push(templateAST, templateAST);
      }
      // // 向 fluid 数组添加节点
      if (path.node.type === 'ObjectProperty' && path.node.key.name === 'fluid') {
        path.node.value.elements.push(templateAST);
      }
    }
  });
}
  1. 使用修改后的ast 生成code
/**
 * 
 * @param {*} ast 
 * @description 根据ast 生成code
 * @returns 
 */
// 添加生成包
const generatePath = '@babel/generator'
const generate = require(generatePath).default;
function generatingCode (ast) {
  return generate(ast)
}
  1. 为了快速插入ast,创建ast模版
/**
 * 
 * @param {*} type 模版类型
 * @param {*} title 模版数据
 * @returns 
 * @description 快速生成模版ast
 */
function generatingTemplateAst (code) {
  const ast = generatingAst(`[${code}]`).program.body[0].expression?.elements[0];
  return ast
}
  1. 如何格式不对,可进一步处理格式
// 添加美化包
const prettier = require("prettier");
// 把生成后的code字符串传给prettier(属性自查)
const formattedCode = prettier.format(code, { 
  parser: "babel",
  trailingComma: "es5",
  tabWidth: 2,
  semi: false, 
  printWidth: 300,
  singleQuote: true,
  bracketSpacing: false,
  trailingComma: 'none'
});
  1. 写入修改后的文件
// 添加fs node.js 的包
const fs = require('fs')
fs.writeFile('src/router/a.js', formattedCode, (err) => {
   if (err) throw err;
 });
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值