Tools for minimal TypeScript transpilation of Vue SFCs
Install package:
# npm
npm install vue-sfc-transformer
# pnpm
pnpm install vue-sfc-transformer
import { parse as parseSFC } from '@vue/compiler-sfc'
import { transform } from 'esbuild'
import { preTranspileScriptSetup, transpileVueTemplate } from 'vue-sfc-transformer'
const src = `
<template>
<div v-if="test as any" />
</template>
<script setup lang="ts">
defineProps<{
test?: string
}>()
</script>
`
const sfc = parseSFC(src, {
filename: 'test.vue',
ignoreEmpty: true,
})
// transpile template block
const templateBlockContents = await transpileVueTemplate(
sfc.descriptor.template.content,
sfc.descriptor.template.ast,
sfc.descriptor.template.loc.start.offset,
async (code) => {
const res = await transform(code, { loader: 'ts', target: 'esnext' })
return res.code
},
)
console.log(templateBlockContents)
// <div v-if="test" />
const { content: scriptBlockContents } = await preTranspileScriptSetup(sfc.descriptor, 'test.vue')
console.log(scriptBlockContents)
// defineProps({
// test: { type: String, required: false }
// })
If you are using mkdist
, vue-sfc-transformer
exports a loader you can use:
import { vueLoader } from 'vue-sfc-transformer/mkdist'
mkdist
will automatically use the loader fromvue-sfc-transformer
when you passvue
to theloaders
option and have this package installed.
- Clone this repository
- Enable Corepack using
corepack enable
- Install dependencies using
pnpm install
- Run interactive tests using
pnpm dev
This package was based on the work of contributors to mkdist
, and in particular this PR by @Teages: unjs/mkdist#300.
Made with ❤️
Published under MIT License.