typescript ast 如何删除或修改JSDoc
时间: 2024-03-17 21:42:23 浏览: 19
TypeScript AST(抽象语法树)提供了一些方法来删除或修改 JSDoc 注释。
要删除 JSDoc 注释,可以使用 `ts.addSyntheticLeadingComment` 方法将其替换为一个空注释或删除它。以下是一个例子:
```typescript
import * as ts from "typescript";
const code = `
/**
* This is a JSDoc comment
*/
function sum(a: number, b: number): number {
return a + b;
}
`;
const sourceFile = ts.createSourceFile("test.ts", code, ts.ScriptTarget.Latest);
const functionDeclaration = sourceFile.statements[0] as ts.FunctionDeclaration;
// Remove JSDoc comment
ts.addSyntheticLeadingComment(functionDeclaration, ts.SyntaxKind.MultiLineCommentTrivia, "", true);
```
要修改 JSDoc 注释,可以先删除旧注释,然后使用 `ts.addSyntheticLeadingComment` 方法添加一个新的注释。以下是一个例子:
```typescript
import * as ts from "typescript";
const code = `
/**
* This is a JSDoc comment
*/
function sum(a: number, b: number): number {
return a + b;
}
`;
const sourceFile = ts.createSourceFile("test.ts", code, ts.ScriptTarget.Latest);
const functionDeclaration = sourceFile.statements[0] as ts.FunctionDeclaration;
// Remove old JSDoc comment
ts.addSyntheticLeadingComment(functionDeclaration, ts.SyntaxKind.MultiLineCommentTrivia, "", true);
// Add new JSDoc comment
const newJSDocComment = `
/**
* This is a new JSDoc comment
*/
`;
ts.addSyntheticLeadingComment(functionDeclaration, ts.SyntaxKind.MultiLineCommentTrivia, newJSDocComment, true);
```
请注意,以上示例仅适用于具有 JSDoc 注释的函数声明。如果您想要删除或修改其他类型的节点的 JSDoc 注释,请相应地修改代码。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)