I bet you are already familiar with the terms “code splitting” and “lazy loading”. Let’s take the latter definition from Webpack’s docs:

Lazy, or “on demand”, loading is a great way to optimize your site or application. This practice essentially involves splitting your code at logical breakpoints, and then loading it once the user has done something that requires, or will require, a new block of code. This speeds up the initial load of the application and lightens its overall weight as some blocks may never even be loaded.

This kind of feature should be done by default by the frameworks we use, as some people have suggested. (Also in the React ecosystem)

The meat:

Whenever it’s possible, I’d recommend to use dynamic imports to import components. They will be lazily loaded (by Webpack) when needed.

// Instead of a usual import
import MyComponent from "~/components/MyComponent.js";

// do this
const MyComponent = () => import("~/components/MyComponent.js");

The explanation:

When using Webpack to bundle your application, you may use different ways to work with modules (ES Modules, CJS, AMD…). If you choose the ESM way (which is the recommended), you will have this kind of syntax:

import MyComponent from "~/components/MyComponent.js";

Notice that there are several use cases where we would like to use asyncronous components. As explained by Alex Jover in this article:

  • In component importing
  • In Vue Router, for components mapping
  • In Vuex modules

#vue #vue.js #programming

Dynamic Imports in Vue.js for better performance
16.50 GEEK