-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
6 changed files
with
107 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import { readFileSync } from 'node:fs'; | ||
import { resolve } from 'node:path'; | ||
import * as acorn from 'acorn'; | ||
|
||
/** | ||
* 获取文件的ast语法树 | ||
* @param filePath 文件路径 | ||
* @param options 配置项 | ||
* @returns {acorn.Program} | ||
*/ | ||
export default function getASTTreeOfFile( | ||
filePath: string, | ||
options?: { | ||
cwd?: string; | ||
} & Partial<acorn.Options>, | ||
): acorn.Program { | ||
const { cwd, encoding } = { | ||
encoding: 'utf8' as const, | ||
cwd: process.cwd(), | ||
...options, | ||
}; | ||
const target = typeof cwd !== 'undefined' ? resolve(cwd, filePath) : filePath; | ||
const code = readFileSync(target, { encoding }); | ||
const comments: acorn.Comment[] = []; | ||
const tokens: acorn.Token[] = []; | ||
const ast = acorn.parse(code, { | ||
ecmaVersion: options?.ecmaVersion || 7, | ||
onComment: comments, | ||
onToken: tokens, | ||
locations: true, | ||
...options, | ||
}); | ||
// @ts-expect-error -- expected | ||
ast.comments = comments; | ||
// @ts-expect-error -- expected | ||
ast.tokens = tokens; | ||
return ast; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters