Vue.js Code Splitting With Webpack and Vue Cli 3

August 24, 2018
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) {
        callback(module)
      }
    })
}

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.

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.