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---56# Skill: ES6 Refactor78## 1. Description910ES6 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.1112The 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.1314## 2. Core Capabilities1516### Syntax Modernization17- Convert `var` declarations to `let` or `const` based on reassignment analysis18- Transform traditional function expressions to arrow functions where appropriate19- Replace string concatenation with template literals20- 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)2324### Module System Transformation25- Convert CommonJS `require()` to ES module `import` statements26- Transform `module.exports` to `export`/`export default` syntax27- Deduplicate and organize imports automatically28- Handle dynamic imports for conditional loading29- Preserve named exports and re-exports3031### TypeScript Support32- Preserve type annotations during refactoring33- Improve interface definitions (convert to `type` aliases when appropriate, use generics)34- Enhance type inference opportunities35- Handle JSX syntax for React/TypeScript files36- Maintain declaration file (`.d.ts`) compatibility3738### Code Quality Guarantees39- Output code passes syntax validation via AST parsing40- Preserve original comments and formatting where possible41- Generate properly indented, formatted output consistent with Prettier standards42- Maintain 100% functional equivalence (no behavior changes)43- Provide transformation logging for audit trails4445### Integration Features46- **CLI Interface**: Accept files via stdin or file paths, output to stdout or files47- **Agent Mode**: Structured input/output for OpenClaw workflow integration48- **Dry Run**: Preview changes without writing files49- **Diff Output**: Show unified diffs of transformations50- **Configuration**: Customizable transformation rules via JSON config5152## 3. Out of Scope5354The following are explicitly NOT supported:5556- **Performance optimization**: Only syntax transformations; no algorithmic improvements57- **Framework patterns**: No React hooks, Vue 3 composition API, Angular-specific patterns58- **Non-JS/TS files**: CSS, HTML, JSON, configuration files are ignored59- **Architectural changes**: No restructuring of project layout or module boundaries60- **Testing**: No test generation, test migration, or validation execution61- **Documentation**: No JSDoc generation or comment enhancement62- **Minification**: Output remains human-readable63- **Polyfills**: No runtime compatibility additions6465## 4. Trigger Scenarios6667### Natural Language Triggers68- "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"7778### CLI Commands79```bash80# Refactor a single file81es6-refactor input.js --output output.js8283# Refactor with stdin/stdout84cat legacy.js | es6-refactor > modern.js8586# Dry run with diff87es6-refactor src/ --dry-run --diff8889# Agent mode (used by OpenClaw)90es6-refactor --mode=agent --input=stdin --output=json9192# TypeScript-specific transformations93es6-refactor component.tsx --typescript --strict9495# Batch processing with glob96es6-refactor "src/**/*.js" --output "modernized/{filename}"97```9899### Agent API100```json101{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": true109 }110}111```112113## 5. Required Resources114115### Script Dependencies116- **@babel/core**: AST parsing and code generation117- **@babel/parser**: JavaScript/TypeScript parser with JSX support118- **@babel/traverse**: AST traversal for transformation passes119- **@babel/generator**: Code generation from transformed AST120- **@babel/preset-env**: Feature detection and polyfill guidance121- **@babel/types**: AST node type definitions122- **prettier**: Code formatting consistency123- **commander**: CLI argument parsing124- **glob**: File pattern matching for batch operations125- **recast**: AST manipulation with source map preservation (optional)126127### Reference Data128- **references/patterns.json**: Legacy-to-modern transformation rules129 ```json130 {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 version143 ```json144 {145 "optional-chaining": {146 "introduced": "ES2020",147 "node": "14.0.0",148 "browsers": ["Chrome 80+", "Firefox 74+", "Safari 13.1+"]149 }150 }151 ```152153### Testing Assets154- **assets/examples/**/*.js: Sample legacy code files for validation155- **assets/**/*.d.ts: TypeScript definition files for type checking156- **tests/**/*.test.js: Unit tests for each transformation rule157158### Node.js Runtime159- Minimum Node.js version: 14.x (for optional chaining support)160- Recommended: 18.x or higher (full ES2022 support)161162## 6. Technical Implementation Notes163164### Transformation Pipeline1651. **Parse**: Use Babel parser to generate AST with accurate location data1662. **Analyze**: Determine code patterns and dependencies (imports, types, reassignments)1673. **Transform**: Apply rule-based modifications to AST nodes1684. **Type-check**: For TypeScript, validate type preservation1695. **Generate**: Output code with formatting and source maps1706. **Validate**: Syntax check output to ensure no errors171172### Rule Engine173- Rules stored in `references/patterns.json` match AST node types174- Each rule includes: pattern selector, replacement template, conditional guards175- Guards inspect scope, variable usage, and type information176- Rules applied in priority order to avoid conflicts177178### Error Handling179- Syntax errors in input code reported with location and message180- Unsupported patterns logged with suggestions181- Partial transformations rolled back on unrecoverable errors182- Exit codes: 0=success, 1=transformation errors, 2=usage error183184## 7. Metadata185186- **Skill ID**: es6-refactor-001187- **Version**: 1.0.0188- **License**: MIT189- **Maintainer**: OpenClaw Skill Factory190- **Repository**: https://github.com/openclaw/skills/tree/main/es6-refactor191- **Keywords**: javascript, typescript, refactor, es6, modernize, code-quality, ast, babel192- **OpenClaw Compatibility**: 1.0+