Skip to content

Latest commit

 

History

History
99 lines (74 loc) · 2.92 KB

README.md

File metadata and controls

99 lines (74 loc) · 2.92 KB

vue-sfc-transformer

npm version npm downloads Github Actions Codecov

Tools for minimal TypeScript transpilation of Vue SFCs

Usage

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 from vue-sfc-transformer when you pass vue to the loaders option and have this package installed.

💻 Development

  • Clone this repository
  • Enable Corepack using corepack enable
  • Install dependencies using pnpm install
  • Run interactive tests using pnpm dev

Credits

This package was based on the work of contributors to mkdist, and in particular this PR by @Teages: unjs/mkdist#300.

License

Made with ❤️

Published under MIT License.