Vue-router Synchronous and asynchronous

/ / ordinary import synchronous loading usage import HelloWorld from "@ / components/HelloWorld. Vue" export default new Router ({routes: [{path: "/", name: "HelloWorld", Component: HelloWorld}]}) export default new Router({routes:[{path: "/", name: "HelloWorld", component: () = > import (" @ / components/HelloWorld. Vue ")})}] / / the require asynchronous loading usage export default new Router ({routes: [{path: "/", name: "HelloWorld", component: resolve => (require(["@/components/HelloWorld.vue"], resolve)) } ] })Copy the code

There are three common ways to load a route, but sometimes several routes need to be loaded together.

const Foo = () => import(/* webpackChunkName: "group-foo" */ './Foo.vue')
const Bar = () => import(/* webpackChunkName: "group-foo" */ './Bar.vue')
const Baz = () => import(/* webpackChunkName: "group-foo" */ './Baz.vue')
Copy the code

Import uses this special comment syntax to group several routes into a group. In fact, I usually group routes in this way, but sometimes I don’t like this comment style.

  • In fact, require can also be grouped using webpack’s require.ensure functionality (this is an old syntax, import is a new syntax), and the following is equivalent to the official documentation.
const Foo = resolve => require.ensure([], () => resolve(require('./Foo.vue')), 'group-foo')
const Bar = resolve => require.ensure([], () => resolve(require('./Bar.vue')), 'group-foo')
const Baz = resolve => require.ensure([], () => resolve(require('./Baz.vue')), 'group-foo')
Copy the code

Parameters will not be detailed, directly attached to the webpack related documentation, easy to understand.

The webPack 2 website reads: Require.ensure () is specific to webpack and replaced by import (). Therefore, require.ensure() is not recommended in WebPack 2. However, this method still works, so it can be briefly introduced. Included in WebPack 1 is also available. Ensure (dependencies: String [], callback: function(require), errorCallback: Function (error), chunkName: String) require.ensure() accepts four parameters: the dependency of the first parameter is an array that represents the dependencies of the module currently required; The second parameter correction is a callback function which is important to note that the callback function is a parameter requirements, by this requirement can introduce other modules within the callback function it is important to note that although this requirement is the callback function parameters, in theory, can change other name, but in fact can't change, Otherwise, WebPack will not be able to handle it statically; The third argument, errorCallback, is easier to understand, handling the errorCallback; The fourth parameter, chunkName, specifies the name of the packaged block.Copy the code