DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Low-Code Approach to Application Development: Exploring Low Code vs. No Code, Tools, Benefits, Challenges, and Design Patterns
  • Misconceptions About No-Code Mobile App Testing
  • 50+ Top Angular Interview Questions and Answers
  • Client-Side Performance Testing

Trending

  • How to Practice TDD With Kotlin
  • Understanding Java Signals
  • Doris: Unifying SQL Dialects for a Seamless Data Query Ecosystem
  • Failure Handling Mechanisms in Microservices and Their Importance
  1. DZone
  2. Coding
  3. JavaScript
  4. Code Splitting With Vue.js and Webpack

Code Splitting With Vue.js and Webpack

Learn how Vue.js and Webpack can be used to split a single page app into more optimally sized files that can be dynamically loaded.

By 
Anthony Gore user avatar
Anthony Gore
DZone Core CORE ·
Updated Feb. 04, 20 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
14.8K Views

Join the DZone community and get the full member experience.

Join For Free

one possible downside to bundling your single page app with webpack is that you can end up with a really big bundle file, sometimes several megabytes in size!

bundle size

 bundle size 


the problem with this is that a user must download the whole file and run it  before  they can see anything on the screen. if the user is on a mobile device with a poor connection this process could take quite some time.

 code splitting  is the idea that a bundle can be fragmented into smaller files allowing the user to only download what code they need, when they need it.

for example, looking at this simple web page, we can identify portions of the app that we don't need on the initial load:

components required for initial page load

 components required for initial page load 


what if we delayed loading these parts of the code until after the initial render? it would allow a user to see and interact with the page much quicker.

in this article, i'll show you how vue.js and webpack can be used to split a single page app into more optimally sized files that can be dynamically loaded.

you may also like:  what's new in vue? 

async components

the key to code splitting a vue.js app is  async components  . these are components where the component definition (including its template, data, methods, etc) is loaded asynchronously.

let's say you're declaring a component using the  component  api, i.e.  vue.component(name, definition)  . rather than having a definition object as the second argument, async components have a function. this function has two notable features:

  1. it's an  executor  for a promise, i.e. it has a  resolve  argument.
  2. it's a  factory function,  i.e. it returns an object (in this case, the component definition).
javascript
 




 x 



1
vue.component('async-component', (resolve) => {
2
  resolve({
3
    template: '<div>async component</div>',
4
    props: [ 'myprop' ]
5
  });
6
});



async components are the first step for code splitting because we now have a mechanism for abstracting sections of our app's code.

dynamic module loading

we'll also need webpack's help. say we abstract our component definition into an es6 module file:

 asynccomponent.js 

javascript
 




xxxxxxxxxx
1



1
export default {
2
  template: '<div>async component</div>',
3
  props: [ 'myprop' ]
4
}



how could we get our vue.js app to load this? you may be tempted to try something like this:

javascript
 




xxxxxxxxxx
1



1
import asynccomponent from './asynccomponent.js'`;
2
vue.component('async-component', asynccomponent);



however, this is  static  and is resolved at compile-time. what we need is a way to  dynamically  load this in a running app if we want to get the benefits of code splitting.

import()

currently, it's not possible to dynamically load a module file with javascript. there is, however, a dynamic module loading function  currently under proposal  for ecmascript called  import()  .

webpack already has an implementation for  import()  and treats it as a code split point, putting the requested module into a separate file when the bundle is created (a separate  chunk  , actually, but think of it as a separate file for now).

 import()  takes the file name as an argument and returns a promise. here's how we'd load our above module:

 main.js 

javascript
 




xxxxxxxxxx
1



1
import(/* webpackchunkname: "async-component" */ './asynccomponent.js')
2
  .then((asynccomponent) => {
3
    console.log(asynccomponent.default.template);
4
    // output: <div>async component</div>
5
  });


note: if you're using babel, you'll need to add the  syntax-dynamic-import  plugin so that babel can properly parse this syntax.

now when you build your project you'll notice the module appears in its own file:

asset and chunk name

 asset and chunk name 


another note: you can give a dynamically imported module chunk a name so its more easily identifiable; simply add a comment before the file name in the same way i've done in the above example.

dynamic component loading

bring the pieces together now: since  import()  returns a promise, we can use it in conjunction with vue's async component functionality. webpack will bundle  asynccomponent  separately and will dynamically load it into the app via ajax when the app calls it.

 main.js 

javascript
 




xxxxxxxxxx
1
12



1
import vue from 'vue';
2

          
3
vue.component('async-component', (resolve) => {
4
  import('./asynccomponent.js')
5
    .then((asynccomponent) => {
6
      resolve(asynccomponent.default);
7
    });
8
});
9

          
10
new vue({ 
11
  el: '#app' 
12
});



 index.html 

html
 




xxxxxxxxxx
1



1
<div id="app">
2
  <p>this part is included in the page load</p>
3
  <async-component></async-component>
4
</div>
5
<script src="bundle.main.js"></script>



on the initial load the page will be rendered as:

html
 




xxxxxxxxxx
1



1
<div id="app">
2
  <p>this part is included in the page load</p>
3
</div>



when  main.js  runs it will initiate a request for the async component module (this happens automatically because webpack's  import()  implementation includes code that will load the module with ajax!).

if the ajax call is successful and the module is returned, the promise resolves and the component can be rendered, so vue will now re-render the page:

html
 




xxxxxxxxxx
1



1
<div id="app">
2
  <p>this part is included in the page load</p>
3
  <div>async component</div>
4
</div>



here's a diagram to help you visualize it:

asynccomponent workflow

 asynccomponent workflow 


single file components

the idiosyncratic way to achieve code splitting in vue, however, is to use the beloved  single file component  . here's a refactor of the above code using an sfc.

 asynccomponent.vue 

html
 




xxxxxxxxxx
1



1
<template>
2
  <div>async component</div>
3
</template>
4
<script>
5
  export default {
6
    props: [ 'myprop' ]
7
  }
8
</script>



this syntax for importing is even neater:

javascript
 




xxxxxxxxxx
1



1
new vue({ 
2
  el: '#app',
3
  components: {
4
    asynccomponent: () => import('./asynccomponent.vue')
5
  }
6
});



code splitting architecture

that's the technical part out of the way. the question, now, is how can you architect an app for code splitting?

the most obvious way is by  page  . for example, say you have two pages in your app, a home page and an about page. these pages can be wrapped inside components,  home.vue  and  about.vue,  and these can be the split points of the app.

but there are other ways, for example, you could split any components that are conditionally shown (tabs, modals, drop-down menus, etc.) or that are below the page fold.

for my next article, i'll explore some different code splitting architectures for a vue.js spa, so stay tuned!


further reading

  •  vue tutorial 7 - components  .
  •  how and why we moved to vue.js  .
code style Vue.js mobile app

Published at DZone with permission of Anthony Gore, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Low-Code Approach to Application Development: Exploring Low Code vs. No Code, Tools, Benefits, Challenges, and Design Patterns
  • Misconceptions About No-Code Mobile App Testing
  • 50+ Top Angular Interview Questions and Answers
  • Client-Side Performance Testing

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!