Writing your first plugin.
// ts-macro.config.ts
export default {
plugins: [
{
name: 'volar-plugin-define-style',
resolveVirtualCode({ codes }) {
// declare the `defineStyle` function type for every TS(X) files.
codes.push('declare function defineStyle<T>(style: string): T ')
},
},
],
}
Or You can use createPlugin
to define plugin. also compatibility with @vue/language-tools plugin.
// ts-macro.config.ts
import { createPlugin, replaceRange } from 'ts-macro'
const defineStylePlugin = createPlugin<{ macro: string } | undefined>(
(
{ ts, compilerOptions },
userOptions = vueCompilerOptions?.defineStyle ?? {
macro: 'defineStyle',
}, // Default options
) => {
return {
name: 'volar-plugin-define-style',
resolveVirtualCode({ ast, codes }) {
codes.push(
`declare function ${userOptions.macro}<T>(style: string): T `,
)
ast.forEachChild(function walk(node) {
if (
ts.isCallExpression(node) &&
node.expression.getText(ast) === userOptions.macro
) {
// Add generic type for defineStyle.
codes.replaceRange(
node.arguments.pos - 1,
node.arguments.pos - 1,
// For simple cases, use strings instead of regex to generate types.
'<{ foo: string }>',
)
}
node.forEachChild(walk)
})
},
}
},
)
export default {
plugins: [
defineStylePlugin({
macro: 'defineStyle',
}),
],
}