Skill: ES6 Refactor
1. Description
ES6 Refactor is a code transformation tool that automatically modernizes JavaScript and TypeScript codebases. It converts legacy patterns (var declarations, callbacks, CommonJS) to modern ES6+ equivalents (let/const, async/await, ES modules) while preserving functionality and improving readability.
The skill integrates seamlessly with OpenClaw agent workflows, providing both a CLI for direct use and an API for programmatic access. It's designed for developers who need to upgrade codebases quickly without manual refactoring, ensuring consistency and adherence to modern best practices.
2. Core Capabilities
Syntax Modernization
- Convert
var declarations to let or const based on reassignment analysis
- Transform traditional function expressions to arrow functions where appropriate
- Replace string concatenation with template literals
- Convert
for loops to array methods (map, filter, reduce, forEach)
- Modernize object manipulation (computed properties, shorthand methods, destructuring)
- Update conditional patterns (ternary operators, optional chaining, nullish coalescing)
Module System Transformation
- Convert CommonJS
require() to ES module import statements
- Transform
module.exports to export/export default syntax
- Deduplicate and organize imports automatically
- Handle dynamic imports for conditional loading
- Preserve named exports and re-exports
TypeScript Support
- Preserve type annotations during refactoring
- Improve interface definitions (convert to
type aliases when appropriate, use generics)
- Enhance type inference opportunities
- Handle JSX syntax for React/TypeScript files
- Maintain declaration file (
.d.ts) compatibility
Code Quality Guarantees
- Output code passes syntax validation via AST parsing
- Preserve original comments and formatting where possible
- Generate properly indented, formatted output consistent with Prettier standards
- Maintain 100% functional equivalence (no behavior changes)
- Provide transformation logging for audit trails
Integration Features
- CLI Interface: Accept files via stdin or file paths, output to stdout or files
- Agent Mode: Structured input/output for OpenClaw workflow integration
- Dry Run: Preview changes without writing files
- Diff Output: Show unified diffs of transformations
- Configuration: Customizable transformation rules via JSON config
3. Out of Scope
The following are explicitly NOT supported:
- Performance optimization: Only syntax transformations; no algorithmic improvements
- Framework patterns: No React hooks, Vue 3 composition API, Angular-specific patterns
- Non-JS/TS files: CSS, HTML, JSON, configuration files are ignored
- Architectural changes: No restructuring of project layout or module boundaries
- Testing: No test generation, test migration, or validation execution
- Documentation: No JSDoc generation or comment enhancement
- Minification: Output remains human-readable
- Polyfills: No runtime compatibility additions
4. Trigger Scenarios
Natural Language Triggers
- "Refactor this code to use modern JavaScript"
- "Convert this to ES6+ syntax"
- "Update this JavaScript to use arrow functions and destructuring"
- "Modernize this TypeScript code"
- "Automatically refactor legacy JavaScript patterns"
- "Convert CommonJS to ES modules"
- "Replace var with let/const throughout this code"
- "Transform async callbacks to promises/async-await"
- "Upgrade this codebase to ES2020"
CLI Commands
# Refactor a single file
es6-refactor input.js --output output.js
# Refactor with stdin/stdout
cat legacy.js | es6-refactor > modern.js
# Dry run with diff
es6-refactor src/ --dry-run --diff
# Agent mode (used by OpenClaw)
es6-refactor --mode=agent --input=stdin --output=json
# TypeScript-specific transformations
es6-refactor component.tsx --typescript --strict
# Batch processing with glob
es6-refactor "src/**/*.js" --output "modernized/{filename}"
Agent API
{
"action": "refactor",
"code": "var x = 1; function foo() { return x; }",
"language": "javascript",
"target": "es2020",
"options": {
"preserveComments": true,
"formatOutput": true
}
}
5. Required Resources
Script Dependencies
- @babel/core: AST parsing and code generation
- @babel/parser: JavaScript/TypeScript parser with JSX support
- @babel/traverse: AST traversal for transformation passes
- @babel/generator: Code generation from transformed AST
- @babel/preset-env: Feature detection and polyfill guidance
- @babel/types: AST node type definitions
- prettier: Code formatting consistency
- commander: CLI argument parsing
- glob: File pattern matching for batch operations
- recast: AST manipulation with source map preservation (optional)
Reference Data
- references/patterns.json: Legacy-to-modern transformation rules
{
"var-to-const": {
"pattern": "var {identifier} = {value}",
"replace": "const {identifier} = {value}",
"conditions": ["no-reassignment"]
},
"callback-to-promise": {
"pattern": "{func}(arg, function(result) { {body} })",
"replace": "async function wrapper() { const result = await {func}(arg); {body} }"
}
}
- references/es6-features.json: Feature compatibility matrix by Node/Browser version
{
"optional-chaining": {
"introduced": "ES2020",
"node": "14.0.0",
"browsers": ["Chrome 80+", "Firefox 74+", "Safari 13.1+"]
}
}
Testing Assets
- assets/examples//*.js: Sample legacy code files for validation
- assets//*.d.ts: TypeScript definition files for type checking
- tests//*.test.js: Unit tests for each transformation rule
Node.js Runtime
- Minimum Node.js version: 14.x (for optional chaining support)
- Recommended: 18.x or higher (full ES2022 support)
6. Technical Implementation Notes
Transformation Pipeline
- Parse: Use Babel parser to generate AST with accurate location data
- Analyze: Determine code patterns and dependencies (imports, types, reassignments)
- Transform: Apply rule-based modifications to AST nodes
- Type-check: For TypeScript, validate type preservation
- Generate: Output code with formatting and source maps
- Validate: Syntax check output to ensure no errors
Rule Engine
- Rules stored in
references/patterns.json match AST node types
- Each rule includes: pattern selector, replacement template, conditional guards
- Guards inspect scope, variable usage, and type information
- Rules applied in priority order to avoid conflicts
Error Handling
- Syntax errors in input code reported with location and message
- Unsupported patterns logged with suggestions
- Partial transformations rolled back on unrecoverable errors
- Exit codes: 0=success, 1=transformation errors, 2=usage error
7. Metadata
1---2name: es6-refactor3description: Automatically refactor JavaScript/TypeScript code to use modern ES6+ patterns and features4---5
6# Skill: ES6 Refactor
7
8## 1. Description
9
10ES6 Refactor is a code transformation tool that automatically modernizes JavaScript and TypeScript codebases. It converts legacy patterns (var declarations, callbacks, CommonJS) to modern ES6+ equivalents (let/const, async/await, ES modules) while preserving functionality and improving readability.
11
12The skill integrates seamlessly with OpenClaw agent workflows, providing both a CLI for direct use and an API for programmatic access. It's designed for developers who need to upgrade codebases quickly without manual refactoring, ensuring consistency and adherence to modern best practices.
13
14## 2. Core Capabilities
15
16### Syntax Modernization
17- Convert `var` declarations to `let` or `const` based on reassignment analysis
18- Transform traditional function expressions to arrow functions where appropriate
19- Replace string concatenation with template literals
20- Convert `for` loops to array methods (`map`, `filter`, `reduce`, `forEach`)
21- Modernize object manipulation (computed properties, shorthand methods, destructuring)
22- Update conditional patterns (ternary operators, optional chaining, nullish coalescing)
23
24### Module System Transformation
25- Convert CommonJS `require()` to ES module `import` statements
26- Transform `module.exports` to `export`/`export default` syntax
27- Deduplicate and organize imports automatically
28- Handle dynamic imports for conditional loading
29- Preserve named exports and re-exports
30
31### TypeScript Support
32- Preserve type annotations during refactoring
33- Improve interface definitions (convert to `type` aliases when appropriate, use generics)
34- Enhance type inference opportunities
35- Handle JSX syntax for React/TypeScript files
36- Maintain declaration file (`.d.ts`) compatibility
37
38### Code Quality Guarantees
39- Output code passes syntax validation via AST parsing
40- Preserve original comments and formatting where possible
41- Generate properly indented, formatted output consistent with Prettier standards
42- Maintain 100% functional equivalence (no behavior changes)
43- Provide transformation logging for audit trails
44
45### Integration Features
46- **CLI Interface**: Accept files via stdin or file paths, output to stdout or files
47- **Agent Mode**: Structured input/output for OpenClaw workflow integration
48- **Dry Run**: Preview changes without writing files
49- **Diff Output**: Show unified diffs of transformations
50- **Configuration**: Customizable transformation rules via JSON config
51
52## 3. Out of Scope
53
54The following are explicitly NOT supported:
55
56- **Performance optimization**: Only syntax transformations; no algorithmic improvements
57- **Framework patterns**: No React hooks, Vue 3 composition API, Angular-specific patterns
58- **Non-JS/TS files**: CSS, HTML, JSON, configuration files are ignored
59- **Architectural changes**: No restructuring of project layout or module boundaries
60- **Testing**: No test generation, test migration, or validation execution
61- **Documentation**: No JSDoc generation or comment enhancement
62- **Minification**: Output remains human-readable
63- **Polyfills**: No runtime compatibility additions
64
65## 4. Trigger Scenarios
66
67### Natural Language Triggers
68- "Refactor this code to use modern JavaScript"
69- "Convert this to ES6+ syntax"
70- "Update this JavaScript to use arrow functions and destructuring"
71- "Modernize this TypeScript code"
72- "Automatically refactor legacy JavaScript patterns"
73- "Convert CommonJS to ES modules"
74- "Replace var with let/const throughout this code"
75- "Transform async callbacks to promises/async-await"
76- "Upgrade this codebase to ES2020"
77
78### CLI Commands
79```bash
80# Refactor a single file
81es6-refactor input.js --output output.js
82
83# Refactor with stdin/stdout
84cat legacy.js | es6-refactor > modern.js
85
86# Dry run with diff
87es6-refactor src/ --dry-run --diff
88
89# Agent mode (used by OpenClaw)
90es6-refactor --mode=agent --input=stdin --output=json
91
92# TypeScript-specific transformations
93es6-refactor component.tsx --typescript --strict
94
95# Batch processing with glob
96es6-refactor "src/**/*.js" --output "modernized/{filename}"
97```
98
99### Agent API
100```json
101{
102 "action": "refactor",
103 "code": "var x = 1; function foo() { return x; }",
104 "language": "javascript",
105 "target": "es2020",
106 "options": {
107 "preserveComments": true,
108 "formatOutput": true
109 }
110}
111```
112
113## 5. Required Resources
114
115### Script Dependencies
116- **@babel/core**: AST parsing and code generation
117- **@babel/parser**: JavaScript/TypeScript parser with JSX support
118- **@babel/traverse**: AST traversal for transformation passes
119- **@babel/generator**: Code generation from transformed AST
120- **@babel/preset-env**: Feature detection and polyfill guidance
121- **@babel/types**: AST node type definitions
122- **prettier**: Code formatting consistency
123- **commander**: CLI argument parsing
124- **glob**: File pattern matching for batch operations
125- **recast**: AST manipulation with source map preservation (optional)
126
127### Reference Data
128- **references/patterns.json**: Legacy-to-modern transformation rules
129 ```json
130 {
131 "var-to-const": {
132 "pattern": "var {identifier} = {value}",
133 "replace": "const {identifier} = {value}",
134 "conditions": ["no-reassignment"]
135 },
136 "callback-to-promise": {
137 "pattern": "{func}(arg, function(result) { {body} })",
138 "replace": "async function wrapper() { const result = await {func}(arg); {body} }"
139 }
140 }
141 ```
142- **references/es6-features.json**: Feature compatibility matrix by Node/Browser version
143 ```json
144 {
145 "optional-chaining": {
146 "introduced": "ES2020",
147 "node": "14.0.0",
148 "browsers": ["Chrome 80+", "Firefox 74+", "Safari 13.1+"]
149 }
150 }
151 ```
152
153### Testing Assets
154- **assets/examples/**/*.js: Sample legacy code files for validation
155- **assets/**/*.d.ts: TypeScript definition files for type checking
156- **tests/**/*.test.js: Unit tests for each transformation rule
157
158### Node.js Runtime
159- Minimum Node.js version: 14.x (for optional chaining support)
160- Recommended: 18.x or higher (full ES2022 support)
161
162## 6. Technical Implementation Notes
163
164### Transformation Pipeline
1651. **Parse**: Use Babel parser to generate AST with accurate location data
1662. **Analyze**: Determine code patterns and dependencies (imports, types, reassignments)
1673. **Transform**: Apply rule-based modifications to AST nodes
1684. **Type-check**: For TypeScript, validate type preservation
1695. **Generate**: Output code with formatting and source maps
1706. **Validate**: Syntax check output to ensure no errors
171
172### Rule Engine
173- Rules stored in `references/patterns.json` match AST node types
174- Each rule includes: pattern selector, replacement template, conditional guards
175- Guards inspect scope, variable usage, and type information
176- Rules applied in priority order to avoid conflicts
177
178### Error Handling
179- Syntax errors in input code reported with location and message
180- Unsupported patterns logged with suggestions
181- Partial transformations rolled back on unrecoverable errors
182- Exit codes: 0=success, 1=transformation errors, 2=usage error
183
184## 7. Metadata
185
186- **Skill ID**: es6-refactor-001
187- **Version**: 1.0.0
188- **License**: MIT
189- **Maintainer**: OpenClaw Skill Factory
190- **Repository**: https://github.com/openclaw/skills/tree/main/es6-refactor
191- **Keywords**: javascript, typescript, refactor, es6, modernize, code-quality, ast, babel
192- **OpenClaw Compatibility**: 1.0+