Home > vue-metamorph > transform
transform() function
Parses source code into ASTs, runs codemod plugins against them, and returns the transformed source code. This is the core function of vue-metamorph.
The filename determines how code is parsed: - .vue — Parsed as a Vue SFC (template + scripts + styles) - .js, .jsx, .ts, .tsx — Parsed as JavaScript/TypeScript - .css, .scss, .sass, .less, .styl — Parsed as CSS
Signature:
typescript
export declare function transform(code: string, filename: string, plugins: CodemodPlugin[], opts?: Record<string, any>): TransformResult;Parameters
Parameter | Type | Description |
|---|---|---|
code | string | Source code string |
filename | string | The file name (determines parser selection) |
plugins | List of codemod plugins to run | |
opts | Record<string, any> | (Optional) Additional options passed through to plugins |
Returns:
Object with code (transformed source) and stats (per-plugin transform counts)
Example
ts
import { transform, type CodemodPlugin } from 'vue-metamorph';
const myPlugin: CodemodPlugin = {
type: 'codemod',
name: 'my-transform',
transform({ scriptASTs, utils: { traverseScriptAST } }) {
let count = 0;
for (const ast of scriptASTs) {
traverseScriptAST(ast, {
visitLiteral(path) {
if (typeof path.node.value === 'string') {
path.node.value = 'Hello, world!';
count++;
}
return this.traverse(path);
},
});
}
return count;
},
};
const result = transform(sourceCode, 'file.vue', [myPlugin]);
result.code; // transformed source code
result.stats; // [['my-transform', 3]]