find_code 插件 react_vite
const fs = require("fs");
const path = require("path");
const parser = require("@babel/parser");
const traverse = require("@babel/traverse").default;
const generate = require("@babel/generator").default;
// 读取文件内容
const filePath = path.join(__dirname, "index.tsx");
const code = fs.readFileSync(filePath, "utf8");
// 解析代码生成 AST
const ast = parser.parse(code, {
sourceType: "module",
plugins: ["jsx"],
});
// 遍历 AST
// 遍历 AST
traverse(ast, {
JSXOpeningElement(path) {
const line = path.node.loc.start.line;
const pathAttribute = {
type: "JSXAttribute",
name: { type: "JSXIdentifier", name: "path" },
value: {
type: "StringLiteral",
value: `${filePath}:${line}`,
},
};
// 检查是否已经存在 path 属性,如果不存在则添加
const existingPathAttribute = path.node.attributes.find((attr) => {
return (
attr.name &&
attr.name.type === "JSXIdentifier" &&
attr.name.name === "path"
);
});
if (!existingPathAttribute) {
path.node.attributes.push(pathAttribute);
}
},
});
// 生成新代码,设置 retainLines 为 true 避免生成不必要的转义序列
const { code: newCode } = generate(ast, {
retainLines: true,
jsescOption: {
minimal: true,
},
});
// 写入文件
fs.writeFileSync(filePath, newCode, "utf8");
console.log("代码修改完成");
// module
import fs from "fs/promises";
import path from "path";
import parser from "@babel/parser";
import traverse from "@babel/traverse";
import generate from "@babel/generator";
// 定义处理文件的异步函数
async function processFile(filePath) {
try {
// 读取文件内容
const code = await fs.readFile(filePath, "utf8");
// 解析代码生成 AST
const ast = parser.parse(code, {
sourceType: "module",
plugins: ["jsx"],
});
// 遍历 AST
traverse.default(ast, {
JSXOpeningElement(path) {
const line = path?.node?.loc?.start?.line;
const pathAttribute = {
type: "JSXAttribute",
name: { type: "JSXIdentifier", name: "path" },
value: {
type: "StringLiteral",
value: `${filePath}:${line}`,
},
};
// 检查是否已经存在 path 属性,如果不存在则添加
const existingPathAttribute = path.node.attributes.find((attr) => {
return (
attr?.name &&
attr?.name.type === "JSXIdentifier" &&
attr?.name.name === "path"
);
});
if (!existingPathAttribute) {
path.node.attributes.push(pathAttribute);
}
},
});
// 生成新代码,设置 retainLines 为 true 避免生成不必要的转义序列
const { code: newCode } = generate.default(ast, {
retainLines: true,
jsescOption: {
minimal: true,
},
});
// 写入文件
await fs.writeFile(filePath, newCode, "utf8");
console.log("代码修改完成");
} catch (error) {
console.error("处理文件时出错:", error);
}
}
// 获取要处理的文件路径
const filePath = path.join(process.cwd(), "node/index.tsx");
// 调用处理函数
processFile(filePath);
代码修改完成效果
import React from "react";
const Test = () => {
return (
<div path="/Users/guojie/跳槽学习文档——速成/vite/node/index.tsx:4">
我是根目录
<div path="/Users/guojie/跳槽学习文档——速成/vite/node/index.tsx:6">
我是子目录
</div>
<span path="/Users/guojie/跳槽学习文档——速成/vite/node/index.tsx:7">
我是孙目录
</span>
</div>
);
};
export default Test;