To improve the maintainability of the code, vue3 is completely rewritten in TypeScript. Because large projects recommend using typed languages, check for type issues during coding.

Vue3.0 uses Monorepo to manage project source code, uses a project to manage multiple packages, and manages the codes of different functions in different packages, so that each functional module is clearly divided and the dependencies between modules are clear. In this way, each module can be released separately, tested separately and used separately.

Package directory structure

Compilers for platform-independent compiler-dom # Rely on core Compiler-SFC # to compile single-file components that rely on core and DOM Compiler-SSR # Server-side render compilers that rely on DOM reactivity # Data responsive system Run-time - Core # and platform-independent runtimes Runtime-test # API for handling native DOM for browser runtime, event for test lightweight runtime, is an object DOM tree, Server-renderer # public API for server rendering shared # internal use size-check # private package Treeshaking then checks the package volume for template-Explorer running the real-time compilation component vue # Build the full vUE, relying on compiler and RuntimeCopy the code

The version of Vue3.0

Vue3.0 was built in different versions, similar to Vue2.0. Unlike VUe2, VUe3 does not build umD modularity, which makes the code more redundant.

Version 3.0 packs SeaJS, esModules, and self-executing functions into separate files, and stores all vue3 builds in Vue Dist.

CJS is a modular way of commonJS, including vue.cjs.js development version and vue.cjs.prod.js compressed production version, they are complete VUE, the difference is whether or not compression.

Global is a global version that can be imported in the browser with the script tag. After importing JS, a global Vue object will be added.

Browser is a native version of the browser, which can be imported from the browser with script type as module.

Bundler doesn’t package all the code, so you need to use the package tool, es Modules. The default version imported through scaffolding is the vue.Runtime.esm-bundler.js version, which is somewhat minimal and can be packaged according to the functionality used by the developer when the project is packaged.

Composition API

The best way to learn Composition is to check out the official RFC, (github.com/vuejs/rfcs)…

Vue2 is great for small to medium sized projects, but there are limitations when using Vue2 for long iterations and maintenance of large projects, where there may be complex components that can be difficult to understand when looking at other people’s components.

Vue2 uses the Options API to create a component using an object that contains Options to describe the component. This method is often used when creating a component. Data, methods, props, lifecycle, etc., are set up to describe the component. If you look at the components developed by others, it may be difficult to understand, because the code of the same function involves multiple configurations such as data and methods. Multiple functions can lead to messy configuration.

Composition API is a new set of apis added to Vue3. It is a set of function-based apis that allow us to organize the logic of components more flexibly. The advantage of this is that you only need to focus on one function when looking at a particular logic. For example, postion only needs to focus on the usePosition function and does not need to focus on other logic.

import { reactive, onMounted, onUnmonted } from 'vue';
function useMousePosition () {
    const position = reactive({ x: 0.y: 0 });
    const update = (e) = > {
        position.x = e.pageX;
        position.y = e.pageY;
    }
    onMounted(() = > {
        window.addEventListener('mousemove', update);
    })
    onUnmounted(() = > {
        window.removeEventListener('mousemove', update)
    })
    return position;
}

export default {
    setup() {
        const position = useMousePosition();
        return {
            position
        }
    }
}
Copy the code

In the Option API, the code of the same logic is split into many places that are not easy to read, while the Composition API ensures that the code of the same logic is gathered in one place and can be made available to other components.

Both apis are supported in Vue3.

Performance improvement

Performance improvements in Vue3 can be described in three ways

  1. Responsive system upgrade

The core of the responsive system in Vue2 uses Object.defineProperty, which iterates over all members of data during initialization, converting properties to GET and set via defineProperty, and recursive traversal if the property is an Object, which is defined at initialization.

Vue3 rewrites the responsive system using Proxy objects. Proexy’s performance is better than defineProperty, and Proxy intercepts all operations of objects without traversing all attributes during initialization. In addition, if there are multiple nested attributes, it only performs recursive processing when accessing a certain attribute.

By default, Proxy can listen for dynamically added attributes, but Vue2 does not have such a function. If dynamically added attributes need to be set by defineProperty again, Vue2 cannot listen for attribute deletion, nor can it listen for array index and length attributes.

  1. Optimize the compilation

The performance of first renders and updates was also significantly improved by optimizing compilation and rewriting of the virtual DOM.

The process of diff in VUe2 will skip the static root node because the content of the static root node will not change, that is, in VUe2, the process of diff is optimized by marking the root node. However, in VUe2, the static node still needs to perform diff, which is not optimized.

Vue3 will mark and promote all static nodes during compilation to improve performance, and then only need to compare the content of dynamic nodes during diff. In addition, vue3 has introduced a new fragment, which is the feature of Fragments. There is no need to create a unique root node in the template, and text content can be directly placed in the template. Or many of the same tags. This feature requires an upgrade to the Vetur plug-in.

That is to say, static nodes will be marked and improved during compilation in VUe3, and static root nodes will be skipped in future diff through patch flag, and content in dynamic nodes only needs to be updated, greatly improving the performance of DIFF.

The cache of event handlers reduces unnecessary update operations.

  1. Source volume

Vue3 removes some of the less commonly used apis, such as inline-template, filter, etc., to make the final code smaller. Filter can be implemented by using method to compute attributes, and tree-shaking is better supported by VUe3. Tree-shaking relies on ES Modules, the modular architecture of ES6.

Through the static analysis at the compile stage, we find the modules that are not introduced, and filter them out directly during packaging to make the volume smaller after packaging. Vue3 was designed with tree-shaking in mind, with built-in components and instructions brought in on demand. In addition, many of the apis in Vue3 support tree-shaking. So some of the new apis in Vue3 will not be packaged if you don’t use them, just the API you use.

But the default core modules are packaged.

Vue3 was designed with performance in mind, through code optimization, compilation optimization or packaging to improve performance.

Vite

The authors who launched Vue with Vue3 also launched their own build tool, Vite. Vite is faster than the webPack-based CLI of the past.

Before we get to Vite, let’s review the way ES Modules are used in browsers.

Modern browsers except IE already support ES Module syntax, that is, use import to import modules, use export to export modules. You can import modules directly from script in a web page by setting type to module.

Script tags labeled module are lazy-loaded by default, similar to adding the defer attribute to script tags. Tags of type module omit defer. It is executed after the current document has been parsed, after the DOM tree has been generated, and before the DOMContentLoaded event.

<script ype="module" src="./index.js"></script>
Copy the code

Vite is fast by using the browser-supported ES Module to speed up development by avoiding packaging in the development environment.

Vite does not need to be packaged in the development environment, because in development mode, Vite uses the browser’s native support ES Module to load modules. Browsers that support ES Module use script tags to load modules, because it does not need to be packaged, so the development mode page is basically open in seconds.

Vue – CLi in development mode is first packed the whole project, if the project is large will be particularly slow, Vue opens a test server, he can intercept browser sends a request, the browser sends a request to the server to obtain the corresponding module, vite can to deal with the browser could other modules such as suffix called. Vue file, It compiles the.vue file on the server and returns the compiled file to the browser.

In this way, Vite has the advantages of fast cold startup, on-demand compilation, hot update of modules, and hot update performance is independent of the total number of modules, no matter how many modules HMR is always faster.

Vite is packaged in production using rollup, which is packaged based on the browser’s native ES Module, without the need to use Babel to convert import to require and some helper functions in response. So the size of the package will be smaller than the size of the WebPack package. Most browsers now support ES Module packaging.

Vite has two ways to create projects, one is to create projects based on VUE3.

npm init vite-app my-project
cd my-project
npm install
npm run dev
Copy the code

Another way is to create projects based on templates that support other frameworks.

npm init vite-app --template react
npm init vite-app --template preact
Copy the code

The Vite-enabled Web server hijacks the.vue request by first parsing the.vue file into a.js file and setting the Content-Type in the response header to Applicaton /javascript to tell the browser that it is returning a JS script.