Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/sxzz/ast-walker-scope
Traverse Babel AST with scope information.
https://github.com/sxzz/ast-walker-scope
Last synced: 5 days ago
JSON representation
Traverse Babel AST with scope information.
- Host: GitHub
- URL: https://github.com/sxzz/ast-walker-scope
- Owner: sxzz
- License: mit
- Created: 2022-07-29T10:13:33.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2024-10-29T18:24:18.000Z (about 2 months ago)
- Last Synced: 2024-10-29T18:36:55.716Z (about 2 months ago)
- Language: TypeScript
- Homepage:
- Size: 474 KB
- Stars: 13
- Watchers: 1
- Forks: 0
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- Funding: .github/FUNDING.yml
- License: LICENSE
Awesome Lists containing this project
README
# ast-walker-scope [![npm](https://img.shields.io/npm/v/ast-walker-scope.svg)](https://npmjs.com/package/ast-walker-scope)
[![Unit Test](https://github.com/sxzz/ast-walker-scope/actions/workflows/unit-test.yml/badge.svg)](https://github.com/sxzz/ast-walker-scope/actions/workflows/unit-test.yml)
Traverse Babel AST with scope information.
Inherited from [estree-walker](https://github.com/Rich-Harris/estree-walker).
## Install
```bash
npm i ast-walker-scope
```## Usage
### Basic Example
For a real example, you can refer to [example.ts](./example.ts)
```ts
import { walk } from 'ast-walker-scope'const code = `
const a = 'root level'{
const a = 'second level'
let secondLevel = true
console.log(a, secondLevel)
}var err = undefined
try {
} catch (err) {
console.log(err)
}console.log(a)
`.trim()walk(code, {
leave(this, node) {
if (node.type === 'CallExpression') {
console.log(`\nLevel: ${this.level}`)
for (const [name, node] of Object.entries(this.scope)) {
console.log(
`variable ${name} is located at line ${node.loc?.start.line}, column ${node.loc?.start.column}`,
)
}
}
},
})
```Output:
```
Level: 2
variable a is located at line 4, column 8
variable secondLevel is located at line 5, column 6Level: 2
variable a is located at line 1, column 6
variable err is located at line 12, column 9Level: 1
variable a is located at line 1, column 6
variable err is located at line 9, column 4
```## Typings
```ts
export type Scope = Record
export interface HookContext extends WalkerContext {
// inherited from estree-walker
skip: () => void
remove: () => void
replace: (node: Node) => void// arguments of estree-walker hook
parent: Node
key: string
index: number// scope info
scope: Scope
scopes: Scope[]
level: number
}
```## Sponsors
## Credits
- [@vue/reactivity-transform](https://github.com/vuejs/core/blob/v3.2.37/packages/reactivity-transform/src/reactivityTransform.ts) - almost copy-like referenced
## License
[MIT](./LICENSE) License © 2022-PRESENT [三咲智子](https://github.com/sxzz)