Trying to implement a typescript compiler transform with the typescript compiler API has been challenging. Despite emitting new Identifier nodes to the final .js file, they appear to lack symbol binding information, resulting in incorrect output.
For instance, consider the following program structure:
A.ts
export class A {
static myMethod() {
return 'value';
}
}
index.ts
import { A } from './A';
export function main() {
const value1 = 'replaceMe';
const value2 = A.myMethod();
const equals = value1 == value2;
}
If we attempt to compile the program above with a specific transformer implementation:
function transformer(program: ts.Program): ts.TransformerFactory<ts.SourceFile> {
return (context: ts.TransformationContext) => (file: ts.SourceFile) => transformFile(program, context, file);
}
// More transformer functions...
Upon pretty-printing the intermediate AST, it appears correct:
import { A } from './A';
export function main() {
const value1 = A.myMethod();
const value2 = A.myMethod();
const equals = value1 == value2;
}
However, the resulting javascript is flawed:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var A_1 = require("./A");
function main() {
var value1 = A.myMethod();
var value2 = A_1.A.myMethod();
var equals = value1 == value2;
}
exports.main = main;
It seems that creating a new identifier with ts.createIdentitier('A')
causes it not to be bound to the same symbol as the existing A
identifier in the file.
Is there a method within the public compiler API to bind a new identifier to an existing symbol?