I use transpileModule to insert a field into Page-data
, but I get result is a js text, miss interface Account
and opt: string | any
. How can I do to get ts text?
const ts = require('typescript')
const factory = ts.factory
const content = `
interface Account {
id: number
displayName: string
version: 1
}
Page({
data: {
name: 'miser',
},
})
Component({
data: {
age: 18,
},
})
function Component(opt: string | any) {}
function Page(opt: any) {}
`
const result = ts.transpileModule(content, {
compilerOptions: {},
transformers: {
before: [visitNodes],
},
})
function visitNodes(ctx) {
const visitor = node => {
if (
ts.isPropertyAssignment(node) &&
node.name.escapedText === 'data' &&
node.parent.parent.expression.escapedText === 'Page'
) {
const newNode = factory.createPropertyAssignment('haha', factory.createStringLiteral('ok'))
node.initializer.properties.push(newNode)
}
return ts.visitEachChild(node, visitor, ctx)
}
return sourceFile => ts.visitNode(sourceFile, visitor)
}
console.log(result.outputText)
// Page({
// data: {
// name: 'miser',
// haha: "ok",
// },
// });
// Component({
// data: {
// age: 18,
// },
// });
// function Component(opt) { }
// function Page(opt) { }