Vue SFC Transformer

0.1.17 · active · verified Sun Apr 19

vue-sfc-transformer provides low-level utilities for transpiling Vue Single File Components (SFCs), specifically focusing on TypeScript syntax within `<script setup>` blocks and template expressions. It aims for minimal transformation, leveraging `esbuild` for the actual code transpilation. The current stable version is `0.1.17`, indicating a pre-1.0 status where API changes might occur in minor releases. This package is actively maintained, receiving frequent bug fixes and minor feature additions as evidenced by its release history, with its last publish being 4 months ago. It is part of the `nuxt-contrib` organization, suggesting its role in the Nuxt ecosystem for build tooling. Its key differentiators include its granular control over SFC block transformation, reliance on `esbuild` for performance, and specific support for handling TypeScript within Vue templates and `script setup` blocks, making it suitable for bundler integrations and custom build pipelines.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `vue-sfc-transformer` to pre-transpile `<script setup lang="ts">` and transform a template block using `esbuild` for a Vue SFC.

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>
`

async function processSFC() {
  const sfc = parseSFC(src, {
    filename: 'test.vue',
    ignoreEmpty: true,
  })

  // Transpile the 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('Transpiled Template:\n', templateBlockContents)
  // Expected output (roughly): <div v-if="test" />

  // Pre-transpile the script setup block
  const { content: scriptBlockContents } = await preTranspileScriptSetup(sfc.descriptor, 'test.vue')
  console.log('Transpiled Script Setup:\n', scriptBlockContents)
  // Expected output (roughly): defineProps({\n//   test: { type: String, required: false }\n// })
}

processSFC().catch(console.error)

view raw JSON →