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