createApp and Mounting: From Application Creation to Initial Render
🎯 Introduction
Every Vue 3 project starts with these two lines:
const app = createApp(App);
app.mount('#app');
What happens behind them? What kind of object does createApp return? What must Vue do when mount is called before your component appears on the page?
By the end, you will be able to:
- Describe the capabilities of the
appobject and where they come from. - Explain why Vue 3 can run in environments such as mini programs and terminals.
- Walk through the execution of
mount. - Trace a component from creation to its initial appearance on the page.
The excerpts use Vue 3.5.x from the GitHub vuejs/core monorepo, primarily packages/runtime-dom/src/index.ts and packages/runtime-core/src/apiCreateApp.ts. Follow along with breakpoints in the environment from the previous article.
🧱 The createApp Entry Point: Where Does app Come From?
How is the app object we use every day created?
Recall Vue 2's new Vue({ el: '#app', ... }). Vue 2 has a shared global Vue constructor, with methods such as Vue.component and Vue.use. Multiple applications on one page therefore share global registrations: registering a component for one application makes it available to another. Vue 3 introduces application instances. Each createApp call returns an independent app; app.component and app.use affect only that application. Compare the two:
// Vue 2: global registration shared by all applications
Vue.component('MyButton', MyButton);
new Vue({ el: '#app' });
// Vue 3: application-scoped registration
const app = createApp(App);
app.component('MyButton', MyButton);
app.mount('#app');
Open packages/runtime-dom/src/index.ts. Rather than implementing application creation directly, createApp delegates to a renderer. A renderer is a set of tools that turns component descriptions into visible output. Calling createRenderer creates those tools. The next section explains why this indirection exists.
// Simplified from packages/runtime-dom/src/index.ts
import { nodeOps } from './nodeOps'; // Browser DOM operations
import { patchProp } from './patchProp'; // Applies element properties, classes, events, etc.
// 1. Create a renderer with DOM-specific operations
const renderer = createRenderer({ ...nodeOps, patchProp });
// 2. The public createApp delegates to the renderer
export const createApp = (...args) => {
const app = renderer.createApp(...args);
// Wrap mount to accept selector strings such as '#app'
const { mount } = app; // Preserve the renderer's original mount
app.mount = (containerOrSelector) => {
// Resolve '#app' to an actual DOM element
const container = normalizeContainer(containerOrSelector);
return mount(container); // Delegate to the original mount
};
return app;
};
Following the call inward, renderer.createApp comes from packages/runtime-core/src/apiCreateApp.ts. This is where the app object is created:
// Simplified from packages/runtime-core/src/apiCreateApp.ts
export function createAppAPI(render) {
// createApp(App) calls this function
return function createApp(rootComponent, rootProps = null) {
const app = {
_component: rootComponent, // The root component passed as App
_props: rootProps, // Props for the root component
_container: null, // Assigned during mounting
config: {}, // Application-wide configuration, such as error handling
provides: {}, // Application-level provided values
use(plugin) {
/* Install a plugin, such as the router */
},
mixin(mixin) {
/* Register an application-wide mixin */
},
component(name, component) {
/* Register an application-wide component */
},
mount(rootContainer) {
/* Mount the application; explained below */
},
unmount() {
/* Unmount the application */
},
};
return app;
};
}
app is an ordinary object with methods such as use, mixin, component, and mount, plus internal fields such as _component and _container. Each API is a function on this object.
app itself, allowing chains such as createApp(App).use(router).mount('#app').🧱 createRenderer and Cross-Platform Design
Why obtain createApp from a renderer? Vue 3 separates general component-rendering logic from platform-specific DOM operations. The general logic lives in runtime-core, without depending on document. Operations such as creating elements, setting properties, and inserting nodes are supplied by the platform through createRenderer options.
In particular, runtime-core handles component creation and updates after state changes. The platform supplies the concrete node operations. For browsers, these are defined in nodeOps:
// Simplified from packages/runtime-dom/src/nodeOps.ts
export const nodeOps = {
// Insert a node
insert: (child, parent, anchor) => {
parent.insertBefore(child, anchor || null);
},
// Remove a node
remove: (child) => {
const parent = child.parentNode;
if (parent) parent.removeChild(child);
},
// Create elements and text nodes
createElement: (tag) => document.createElement(tag),
createText: (text) => document.createTextNode(text),
// ... Other operations include querySelector
};
These are familiar native DOM APIs. Passing them to createRenderer({ ...nodeOps, patchProp }) gives the renderer the operations needed for a browser. Replace those operations and the same core can target another environment:
- Browser: inject
nodeOpsto get the Vue renderer you normally use. - Mini programs, terminals, or Canvas: inject a different set of platform operations without changing the core logic. Community renderers for mini programs and terminals follow this approach.
hostInsert and hostCreateElement are aliases for operations supplied by the host platform. In the browser renderer, look in nodeOps for their implementations.🧱 What app.mount Does
Now that we know where app comes from, let's follow app.mount('#app'). First, two terms:
- vnode (virtual node): an ordinary JavaScript object describing a UI element, for example a
divcontaining text. It is a rendering description, not an actual DOM node. - patch: the process of creating or updating real DOM from a vnode description. The initial render creates everything; later updates change the necessary parts.
With these terms established, the simplified mount is straightforward:
// Simplified from mount in packages/runtime-core/src/apiCreateApp.ts
mount(rootContainer) {
// 1. Describe the root component as a vnode
const vnode = createVNode(rootComponent, rootProps);
// 2. Attach application context for features such as provide/inject
vnode.appContext = app._context;
// 3. Enter patching through render to create the DOM
render(vnode, rootContainer);
// 4. Record the container and mark it as mounted
app._container = rootContainer;
rootContainer.__vue_app__ = app;
// 5. Return the root component's public instance proxy
return vnode.component.proxy;
}
Step by step:
- Create a vnode.
createVNodewraps the root component in a rendering description. No DOM operations have occurred yet. Article 7 covers vnodes in detail. - Attach application context. This holds application-wide components, configuration, and
provides, making the relevant context available throughout the component tree forprovide/inject. - Start rendering.
renderis the renderer's core entry point. It invokes patching to turn the vnode into DOM inside the container. - Mark the container. The
__vue_app__property helps Vue DevTools locate the application and identifies a container already used by an app. - Return the public proxy.
mountreturns the root component instance'sproxy, rather thanapp. This proxy provides access to the component instance, forwarding property and method access to its internal state. It is the access layer used by Options APIthisand byvm.xxx.
app.mount('#app') does not return app, so you cannot continue chaining use afterward. Install plugins before calling mount.🧱 What Happens During the Initial Render?
The render function enters patching. On the initial render there is no old vnode, so patching takes the fresh-mount path. When it encounters a component vnode, the main steps are:
// Simplified component mounting from packages/runtime-core/src/renderer.ts
function mountComponent(vnode, container) {
// 1. Create the object holding this component's information
const instance = createComponentInstance(vnode);
vnode.component = instance;
// 2. Run setup() and process its returned state or render function
setupComponent(instance);
// 3. Create the render effect and render the actual DOM
setupRenderEffect(instance, vnode, container);
}
Each step has a distinct role:
- Create the instance.
instanceis an ordinary JavaScript object holding component information, including setup results, lifecycle information, and rendering state. - Run setup. Vue calls your
setup()and makes its returned state available to the template. - Create the render effect. An
effectis, in simple terms, a function that can rerun automatically. The render effect executes the component's render function and recursively patches its subtree, creating DOM and inserting it into the container.
This is only the main flow. Article 4 explains how effects connect to reactive data and rerun when it changes; article 7 explains how patching compares and updates vnodes. For now, remember the order: instance → setup → render effect → visible DOM.
createComponentInstance, setupComponent, and setupRenderEffect, then refresh. They will be reached in that order.⚡ Comparing Initialization with Vue 2
If you followed _init from new Vue() in the Vue 2 source code course, this table highlights the differences:
| Aspect | Vue 2 | Vue 3 |
|---|---|---|
| Entry point | new Vue(options) constructor | createApp(App) returns an application instance |
| Mounting API | el option or $mount('#app') | app.mount('#app') |
| Global configuration | Shared constructor, such as Vue.use | Application-scoped methods such as app.use |
| Platform coupling | Core and browser-specific code coupled within the repository | Separate runtime-core and runtime-dom packages |
The first and third rows capture the main change: Vue 3 replaces a shared global Vue with independent applications, each with its own component registry, plugins, and configuration.
❓ Questions and Answers
Q1: What is the fundamental difference between createApp and Vue 2's new Vue?
new Vue creates a component instance, with global configuration on the shared Vue constructor. createApp creates an application instance that owns its configuration, components, and plugins. Multiple independent Vue 3 applications can coexist on one page much more easily.
Q2: Why does mount return the component proxy rather than app?
After mounting, you often need to access the root component's methods or state. With const vm = app.mount('#app'), vm provides access to what the root component exposes. You already have a reference to app.
Q3: What happens if createApp is called multiple times?
Each call creates a fresh, independent application with its own component registry, plugins, and provided values. This supports scenarios such as micro-frontends or multiple Vue widgets on one page.
Q4: Can the same container be mounted twice?
A container should host only one mounted application. Vue checks the __vue_app__ marker and warns about an existing app. Unmount the existing application with app.unmount() before mounting a replacement.
Q5: Does createApp(App) perform any DOM operations?
No. It creates the application and records the root component. Vnode creation and DOM rendering happen when mount is called. You can install plugins and register application-wide components between these calls.
🧪 Exercise
Write a mini createApp in roughly 30 lines. Return an app object with a mount method. Inside mount, execute the root component's setup and render, then render the result into the selected container. Save this as an HTML file and open it in a browser.
<div id="app"></div>
<script>
function createApp(rootComponent) {
// Your code here: return { mount }
// mount should:
// 1. Run rootComponent.setup() to obtain state
// 2. Call rootComponent.render(state) to obtain { tag, children }
// 3. Create real DOM and insert it into the container
// 4. Set the container's __vue_app__ marker
}
const App = {
setup() {
return { message: 'hello mini vue3' };
},
render(state) {
return { tag: 'h1', children: state.message };
},
};
createApp(App).mount('#app');
</script>
For an extra challenge, support nested child arrays, such as { tag: 'div', children: [{ tag: 'p', children: 'hi' }] }. Processing these recursively gives you the beginnings of recursive mounting in patch.
🎉 You can now trace createApp through the initial render! Next, we will explore the core of Vue 3 reactivity: how Proxy intercepts reads and writes to turn ordinary objects into reactive data.
Introduction to Vue 3 Source Code
Learn why to read Vue 3 source code, navigate the vuejs/core repository, and set up a local debugging environment.
Proxy-Based Reactivity
Learn how Vue 3 implements reactive with Proxy, why it uses lazy wrapping and caching, and which Vue 2 limitations this approach addresses.
