0
# Command Line Interface
1
2
Convenient command-line interface for running transformations on files directly from the shell or within scripts.
3
4
## Capabilities
5
6
### Run Function
7
8
Execute transformations on files using a transformer function, typically used for command-line tools and scripts.
9
10
```typescript { .api }
11
/**
12
* Run a transformer function on files from command line arguments
13
* @param transformer - Function that transforms AST and calls callback with result
14
* @param options - Optional configuration including writeback function
15
*/
16
function run(transformer: Transformer, options?: RunOptions): void;
17
18
interface Transformer {
19
/** Transform AST and call callback with modified AST */
20
(ast: types.ASTNode, callback: (ast: types.ASTNode) => void): void;
21
}
22
23
interface RunOptions extends Options {
24
/** Custom function to handle output (default: write to stdout) */
25
writeback?(code: string): void;
26
}
27
```
28
29
**Usage Examples:**
30
31
```typescript
32
import { run, types, visit } from "recast";
33
34
// Transform arrow functions to regular functions
35
function transformer(ast: types.ASTNode, callback: (ast: types.ASTNode) => void) {
36
visit(ast, {
37
visitArrowFunctionExpression(path) {
38
const node = path.value;
39
const func = types.builders.functionExpression(
40
null,
41
node.params,
42
types.builders.blockStatement([
43
types.builders.returnStatement(node.body)
44
])
45
);
46
path.replace(func);
47
this.traverse(path);
48
}
49
});
50
callback(ast);
51
}
52
53
// Run on command line argument file
54
// Usage: node my-transformer.js input.js
55
run(transformer);
56
57
// Run with custom writeback
58
run(transformer, {
59
writeback(code) {
60
require('fs').writeFileSync('output.js', code);
61
}
62
});
63
```
64
65
### Command Line Usage Patterns
66
67
The `run` function automatically handles file input and output for command-line tools.
68
69
**Basic Pattern:**
70
71
```typescript
72
#!/usr/bin/env node
73
import { run, types, visit } from "recast";
74
75
function myTransformer(ast: types.ASTNode, callback: (ast: types.ASTNode) => void) {
76
// Your transformation logic here
77
visit(ast, {
78
// visitor methods
79
});
80
callback(ast);
81
}
82
83
// Run on file from command line argument
84
run(myTransformer);
85
```
86
87
**Usage from shell:**
88
```bash
89
node my-transformer.js input.js > output.js
90
```
91
92
### File Processing Workflow
93
94
The `run` function handles the complete file processing pipeline:
95
96
1. **File Reading**: Reads the file specified as the first command-line argument
97
2. **Parsing**: Parses the file content into an AST using recast's parser
98
3. **Transformation**: Calls the provided transformer function with the AST
99
4. **Printing**: Converts the transformed AST back to code
100
5. **Output**: Writes the result to stdout or custom writeback function
101
102
**Error Handling:**
103
104
```typescript
105
function robustTransformer(ast: types.ASTNode, callback: (ast: types.ASTNode) => void) {
106
try {
107
// Your transformation logic
108
visit(ast, {
109
visitFunctionDeclaration(path) {
110
// Transform functions
111
this.traverse(path);
112
}
113
});
114
callback(ast);
115
} catch (error) {
116
console.error("Transformation failed:", error.message);
117
// Return original AST on error
118
callback(ast);
119
}
120
}
121
```
122
123
### Advanced CLI Options
124
125
Combining CLI functionality with parser and printer options.
126
127
```typescript
128
import { run, Options } from "recast";
129
130
const transformOptions: Options = {
131
parser: require("recast/parsers/typescript"),
132
tabWidth: 2,
133
quote: "single"
134
};
135
136
function typeScriptTransformer(ast: types.ASTNode, callback: (ast: types.ASTNode) => void) {
137
// TypeScript-specific transformations
138
callback(ast);
139
}
140
141
run(typeScriptTransformer, transformOptions);
142
```
143
144
### Integration with Build Tools
145
146
Using the CLI interface within build processes and npm scripts.
147
148
**package.json scripts:**
149
150
```json
151
{
152
"scripts": {
153
"transform": "node scripts/transformer.js",
154
"transform:all": "find src -name '*.js' -exec node scripts/transformer.js {} \\;"
155
}
156
}
157
```
158
159
**Build script example:**
160
161
```typescript
162
// scripts/transformer.js
163
import { run, types, visit } from "recast";
164
import fs from "fs";
165
import path from "path";
166
167
function buildTransformer(ast: types.ASTNode, callback: (ast: types.ASTNode) => void) {
168
visit(ast, {
169
visitCallExpression(path) {
170
// Replace debug calls in production
171
if (process.env.NODE_ENV === 'production') {
172
const node = path.value;
173
if (node.callee.name === 'debug') {
174
path.prune(); // Remove debug calls
175
return false;
176
}
177
}
178
this.traverse(path);
179
}
180
});
181
callback(ast);
182
}
183
184
run(buildTransformer, {
185
writeback(code) {
186
const inputFile = process.argv[2];
187
const outputFile = inputFile.replace(/\.js$/, '.min.js');
188
fs.writeFileSync(outputFile, code);
189
console.log(`Transformed ${inputFile} -> ${outputFile}`);
190
}
191
});
192
```