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 vue-metamorph parses the code:
.vue— Parsed as a Vue SFC, which covers the template, the scripts, and the styles. -.js,.jsx,.ts,.tsx— Parsed as JavaScript or TypeScript. -.css,.scss,.sass,.less,.styl— Parsed as CSS.
Signature:
typescript
export declare function transform(code: string, filename: string, plugins: CodemodPlugin[], opts?: PluginOptions): TransformResult;Parameters
Parameter | Type | Description |
|---|---|---|
code | string | The source code. |
filename | string | The name of the file. vue-metamorph selects a parser based on this name. |
plugins | The codemod plugins to run. | |
opts | (Optional) Extra options to pass through to the plugins. |
Returns:
An object with a code property, which holds the transformed source, and a stats property, which holds the 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]]