Vue SFC Parser

0.1.2 · active · verified Tue Apr 21

vue-sfc-parser is a utility library for parsing Vue.js Single File Components (SFCs) specifically designed for static analysis workflows. It provides a structured representation of an SFC, similar to `vue-template-compiler`'s `parseComponent` function, but enhances it with additional helper methods on `SFCBlock` objects, such as `calcGlobalOffset` and `calcGlobalRange`, to facilitate mapping block-specific positions back to the overall file position. Currently at version 0.1.2, the library also includes a `createDiffWatcher` API for efficiently detecting changes within individual SFC blocks, enabling sophisticated hot-reloading or analysis tools. Its release cadence is ad-hoc, reflecting its early development stage. A key differentiator is its focus on providing precise positional data and change detection, which is crucial for linters, language servers, and build tools that operate on Vue SFCs.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates parsing a Vue SFC, accessing its blocks, and using `calcGlobalOffset` to map block-relative positions to global file positions.

import { parseComponent } from 'vue-sfc-parser';

const code = `
<template>
  <p>Hello from SFC!</p>
</template>

<script lang="ts">
export default {
  data() {
    return { msg: 'world' };
  }
}
</script>

<style scoped>
p {
  color: blue;
}
</style>
`;

const sfcDescriptor = parseComponent(code);

if (sfcDescriptor.template) {
  console.log('Template content:', sfcDescriptor.template.content);
  // Calculate global offset for 'Hello' (5 chars into template content)
  const templateOffset = sfcDescriptor.template.content.indexOf('Hello');
  const globalOffset = sfcDescriptor.template.calcGlobalOffset(templateOffset);
  console.log(`Global offset for 'Hello': ${globalOffset}`);
}

if (sfcDescriptor.script) {
  console.log('Script content:', sfcDescriptor.script.content);
  const scriptOffset = sfcDescriptor.script.content.indexOf('msg');
  const globalOffset = sfcDescriptor.script.calcGlobalOffset(scriptOffset);
  console.log(`Global offset for 'msg': ${globalOffset}`);
}

if (sfcDescriptor.styles.length > 0) {
  console.log('First style content:', sfcDescriptor.styles[0].content);
}

view raw JSON →