Usage Examples
Basic Usage
This guide will walk you through the fundamental concepts and basic usage of Mutates.
Project Setup
Every Mutates operation starts with creating a project:
import { createProject, saveProject } from '@mutates/core';
// Initialize the project
createProject();
// Make your modifications...
// Save changes
saveProject();
Common Operations
Working with Files
import { createSourceFile } from '@mutates/core';
// Create a new file
createSourceFile(
'src/example.ts',
`
export class Example {
constructor() {}
}
`,
);
Adding Classes
import { addClasses } from '@mutates/core';
addClasses('src/example.ts', {
name: 'MyService',
isExported: true,
properties: [
{
name: 'value',
type: 'string',
initializer: '"default"',
},
],
});
Modifying Existing Code
import { editClasses, getClasses } from '@mutates/core';
// Find classes
const classes = getClasses({ pattern: 'src/**/*.ts' });
// Modify them
editClasses(classes, (structure) => ({
...structure,
isExported: true,
}));
Working with Different Elements
Functions
import { addFunctions } from '@mutates/core';
addFunctions('src/utils.ts', {
name: 'helper',
parameters: [{ name: 'value', type: 'string' }],
returnType: 'string',
statements: 'return value.toUpperCase();',
});
Properties
import { addProperties } from '@mutates/core';
addProperties(targetClass, {
name: 'config',
type: 'Configuration',
hasQuestionToken: true,
});
Best Practices
- Always wrap operations in try-catch:
try {
createProject();
// operations...
saveProject();
} catch (error) {
console.error('Error:', error);
}
- Use pattern matching effectively:
getClasses({ pattern: 'src/**/*service.ts' });
- Clean up resources:
import { resetActiveProject } from '@mutates/core';
try {
// operations...
} finally {
resetActiveProject();
}
Next Steps
- Learn about Advanced Usage
- Explore Framework Integrations
- Understand AST Manipulation