I'm using typescript API to create a custom syntax file preprocessor, just like svelte and vue do.
So, I input my custom file with a custom syntax and use ts.transform
function to walk through the AST tree and change what I need to change.
But what I didn't find in ts docs is, how can I generate source maps from my input file string to the output result string?
const sourceFile = ts.createSourceFile(
"index.ts",
fileContent, // file input string
ts.ScriptTarget.ESNext,
false,
ts.ScriptKind.TSX
);
const result = ts.transform(sourceFile, [transformer]); // my custom transformer function
const resultStr = printer.printFile(result.transformed[0]); // the output file string
// how to get sourcemaps for "resultStr"?
Stumbled up on this yesterday as i had the same issue when using ts.transform
. So I looked up how ts-jest was able to generate the same when running in isolatedModules.
After looking into ts-jest code base found that if we use ts.transpileModule
instead of ts.transform
, the result output includes source map as well.
Here is what i used which returned source maps as well (with TS 4.7.x), -
const transformedOutput = ts.transpileModule(sourceText, {
fileName: sourcePath,
transformers: {
before: [transformer]
},
compilerOptions: {
target: ts.ScriptTarget.ES2015,
module: ts.ModuleKind.ESNext,
isolatedModules: true,
sourceMap: true
}
});
console.log('Transformed Code - \n', transformedOutput .outputText);
console.log('Transformed sourcemap - \n', transformedOutput .sourceMapText);
Here is a link to ts-jest codebase with this usage - https://github.com/kulshekhar/ts-jest/blob/main/src/legacy/compiler/ts-compiler.ts#L256