Vue Compiler Overview and Sandbox Compilation Techniques
This article explores the fundamentals of Vue's compilation process, compares Vue 2 and Vue 3 compilers, demonstrates sandbox compilation with code examples, and discusses practical considerations such as handling templates, scripts, styles, and hot‑module reloading, providing developers with insights to effectively integrate Vue compilation in browser environments.
The article begins with a personal preface and then shifts focus to the concept of a compiler, defining it as a program that transforms source code into target code and outlining the typical compilation pipeline.
It then discusses how compilers are used in the frontend, mentioning popular tools such as Babel and Vue's @vue/compiler-sfc, and raises the question of whether these packages alone are sufficient for sandbox compilation.
Vue 2.6 compiler (vue-template-compiler) is introduced, explaining its role in pre‑compiling templates into render functions and its typical usage together with vue-loader. Example code shows a simple SFC and the generated render function.
The article presents the Vue Loader workflow, including how it parses <template> , <script> , and <style> sections, and provides sample code for splitting components and compiling each part.
It then moves to Vue 2.7, noting that although it introduces a new compiler (@vue/compiler-sfc 2.7), it builds upon the Vue 2.6 implementation and still requires a browser‑compatible build.
For Vue 3, the author examines the @vue/compiler-sfc package, highlighting its complete rewrite and the availability of a browser version. Detailed code demonstrates importing the compiler API, handling TypeScript, SCSS, scoped styles, hot‑module reloading, and generating the final component object.
async function compileFile(code, filename) {
const id = hashId(filename);
const { errors, descriptor } = parse(code, { filename, sourceMap: true });
// ... compile script, template, styles ...
return { js: clientCode, setMap: cssObj.setMap };
}Key helper functions such as transformTS , compileFile , doCompileScript , and doCompileTemplate are explained, showing how they parse the SFC, compile scripts (including TypeScript), compile templates, process styles, and assemble the final JavaScript and CSS output.
The final generated component includes render logic, style injection, and HMR support, making it ready to run inside a sandbox environment.
The article concludes by mentioning that similar techniques can be applied to other frameworks (React, CSS, Babel) and promises future posts covering those topics.
Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.