Search code examples
vue.jswebpackvue-cli

Vue How to implement webpack and service-workers


currently, my vue app has a package.json like this:

{
  "name": "App",
  "version": "0.1.2",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
  }
}

In my main.js I have this:

if(process.env.NODE_ENV == 'development')
    Vue.prototype.$http.defaults.baseURL = 'http://127.0.0.1:8000/api'
else
    Vue.prototype.$http.defaults.baseURL = 'https://api.example.net/api'

I would now like to use webpack to build my app and manage certain things. What is the best way to integrate webpack into my project now and optimize it? I would like to use a service-worker to inform the users about a new version every time and ask them to reload the page.


Solution

  • You don't need to integrate Webpack into a Vue CLI scaffolded project. Vue CLI uses Webpack under the hood.

    To configure the underlying Webpack, create vue.config.js with a chainWebpack or configureWebpack property:

    // vue.config.js
    module.exports = {
      configureWebpack: {
        //...
      },
      chainWebpack: config => {
        //...
      }
    }
    

    Regarding the Service Worker, you could use the @vue/cli-plugin-pwa plugin, which can be added to a Vue CLI project with this command:

    $ vue add pwa