Vue 2 Template Compiler

raw JSON →
2.4.8 verified Fri May 01 auth: no javascript deprecated

Pre-compiles Vue 2.0 templates into render functions to avoid runtime compilation overhead and CSP restrictions. Current stable version is 2.7.16, the final Vue 2 release (EOL December 31, 2023). This package is auto-generated from Vue core; for most cases use vue-loader or vueify instead. It supports custom compile-time modules and directives, SFC parsing, and provides compile() and compileToFunctions() APIs. The returned render function uses 'with' and cannot be used in strict mode. Key differentiator: low-level compiler for build tools, distinct from runtime-only Vue builds.

error TypeError: compiler.compile is not a function
cause Using default import when package exports named functions.
fix
Use named import: import { compile } from 'vue-template-compiler'
error SyntaxError: With statement in strict mode
cause Using compiled render code in strict mode context.
fix
Wrap render function in a non-strict function or use compileToFunctions()
error Cannot find module 'vue-template-compiler'
cause Package not installed or wrong import path.
fix
Run npm install vue-template-compiler
deprecated Vue 2 reached End of Life on December 31, 2023. This package will not receive updates.
fix Migrate to Vue 3 and use @vue/compiler-sfc.
gotcha compile() returns render code using 'with' statement, which is forbidden in strict mode and will throw in ES modules or TypeScript with strict mode.
fix Use compileToFunctions() which returns Function objects, or wrap render code in a non-strict function.
gotcha compileToFunctions() uses new Function() and is not CSP-compliant.
fix Use pre-compiled render functions via compile() if CSP is required.
deprecated Options like 'modules' and 'directives' are undocumented and may change; custom modules break compatibility with vue-loader/vueify.
fix Avoid custom compile modules; use standard build tools.
npm install touchui-template-compiler
yarn add touchui-template-compiler
pnpm add touchui-template-compiler

Compiles a Vue 2 template string to render functions and parses a .vue SFC file.

import { compile, parseComponent } from 'vue-template-compiler';
import * as fs from 'fs';

const template = '<div>{{ message }}</div>';
const compiled = compile(template, {
  preserveWhitespace: false
});
console.log('Render function:', compiled.render);
console.log('Static render fns:', compiled.staticRenderFns);
console.log('Errors:', compiled.errors);

// Parse a .vue file
const source = fs.readFileSync('component.vue', 'utf8');
const descriptor = parseComponent(source, { pad: 'line' });
console.log('Template:', descriptor.template?.content);
console.log('Script:', descriptor.script?.content);
console.log('Styles:', descriptor.styles?.length);