mirror of
https://github.com/luzhisheng/js_reverse.git
synced 2025-04-21 12:15:16 +08:00
AST操作之API用法-path路径
This commit is contained in:
parent
aef4e15911
commit
e6a72aae27
@ -227,3 +227,42 @@ var a;
|
|||||||
```
|
```
|
||||||
|
|
||||||
**替换path,单路径可以使用`replaceWith`方法,多路径则使用`replaceWithMultiple`方法**
|
**替换path,单路径可以使用`replaceWith`方法,多路径则使用`replaceWithMultiple`方法**
|
||||||
|
|
||||||
|
需求:把var a = 123; 修改成var a = 3 ,用replaceWith方法
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
const fs = require('fs');
|
||||||
|
const {parse} = require("@babel/parser");
|
||||||
|
const traverse = require("@babel/traverse").default;
|
||||||
|
const generator = require("@babel/generator").default;
|
||||||
|
let encode_file = "./encode.js";
|
||||||
|
|
||||||
|
let js_code = fs.readFileSync(encode_file, {encoding: "utf-8"});
|
||||||
|
let ast = parse(js_code, {
|
||||||
|
sourceType: 'module',
|
||||||
|
});
|
||||||
|
|
||||||
|
const visitor = {
|
||||||
|
enter(path) {
|
||||||
|
if (path.isNumericLiteral() && path.node.value == 123) {
|
||||||
|
path.replaceWith({type: "NumericLiteral", value: 3});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
traverse(ast, visitor);
|
||||||
|
|
||||||
|
// 写入文件
|
||||||
|
let {code} = generator(ast);
|
||||||
|
console.log(code)
|
||||||
|
fs.writeFile('decode.js', code, (err) => {
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
打印内容:
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
var a = 3;
|
||||||
|
```
|
||||||
|
|
||||||
|
注意点,必须加上`&& path.node.value == 123`判断,否则就是无限循环
|
@ -11,8 +11,8 @@ let ast = parse(js_code, {
|
|||||||
|
|
||||||
const visitor = {
|
const visitor = {
|
||||||
enter(path) {
|
enter(path) {
|
||||||
if (path.isNumericLiteral()) {
|
if (path.isNumericLiteral() && path.node.value == 123) {
|
||||||
path.replaceWith({type:"NumericLiteral",value:3});
|
path.replaceWith({type: "NumericLiteral", value: 3});
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user