Vue.js Code Splitting With Webpack and Vue Cli 3

Dynamically load javascript

To dynamically load javascript module/code, use the following syntax.

const consolePromise = import(/* webpackChunkName: "console" */ './modules/console/index')consolePromise.then((module) => {  module = module.default  module.init()})  

If you need to expose Promise to browser javascript which might not support it yet (e.g. IE), you can convert it to a callback.

function loadConsole(callback = null) {
  return import(/* webpackChunkName: "console" */ './modules/console/index')
    .then((module) => {
      module = module.default

      if (callback != null) {

Sample code for ./modules/console/index.js. Content of this javascript or any javascript import by this file shall be bundled together as console.js and loaded dynamically.

export default {  init() {    console.log('I am console')  }}

If you are loading hot reload (http://localhost:8080/app.js) on external server (e.g. nginx), you would want to configure vue.config.js with the following (else the dynamic loading path for console.js would be incorrect).

const path = require('path')const webpack = require('webpack')module.exports = {  devServer: {    headers: {      "Access-Control-Allow-Origin":"\*"    },  },  assetsDir: process.env.NODE_ENV === 'production'    ? 'static/vue'    : 'http://localhost:8080/',  baseUrl: process.env.NODE_ENV === 'production'    ? '/' // mess up assetsDir if this is blank    : 'http://localhost:8080/',}

Notice static/vue for assetsDir for production (npm run build). I am serving css and js from /static/vue/css/(chunk-vendors|app|console).<HASH>.(js|css) on my production server.


❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.