Newer
Older
navi-1 / webclient / vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import { createHash } from 'crypto'
import { copyFileSync, existsSync, readFileSync, readdirSync, writeFileSync } from 'fs'

/**
 * Stamps `__NAVI_BUILD_VERSION__` in dist/sw.js with a digest of index.html +
 * the hashed asset filenames. sw.js is served with Cache-Control: no-store, so
 * its bytes changing on every build makes the browser pick up the new service
 * worker, whose activation evicts caches from previous builds.
 */
function stampServiceWorkerVersion() {
  return {
    name: 'stamp-sw-version',
    closeBundle() {
      const dist = resolve(__dirname, 'dist')
      const distSw = resolve(dist, 'sw.js')
      const publicSw = resolve(__dirname, 'public', 'sw.js')
      // Depending on the Vite version the public/ copy may run after
      // closeBundle — fall back to copying the un-stamped source ourselves.
      if (!existsSync(distSw)) {
        copyFileSync(publicSw, distSw)
      }
      const hash = createHash('sha256')
      hash.update(readFileSync(resolve(dist, 'index.html')))
      for (const name of readdirSync(resolve(dist, 'assets')).sort()) {
        hash.update(name)
      }
      writeFileSync(
        distSw,
        readFileSync(distSw, 'utf8').replaceAll('__NAVI_BUILD_VERSION__', hash.digest('hex').slice(0, 16))
      )
    }
  }
}

export default defineConfig({
  plugins: [vue(), stampServiceWorkerVersion()],
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src'),
      '@kit': resolve(__dirname, 'vendor/gnexus-ui-kit'),
      'gnexus-ui-kit/vue': resolve(__dirname, 'vendor/gnexus-ui-kit/dist/vue/index.js'),
      'gnexus-ui-kit/css': resolve(__dirname, 'vendor/gnexus-ui-kit/dist/css/kit.css')
    }
  },
  css: {
    preprocessorOptions: {
      scss: {
        loadPaths: [
          resolve(__dirname, 'vendor/gnexus-ui-kit/src/scss')
        ]
      }
    }
  },
  build: {
    outDir: resolve(__dirname, 'dist'),
    emptyOutDir: true
  },
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:8099',
        rewrite: path => path.replace(/^\/api/, '')
      },
      '/ws': {
        target: 'ws://localhost:8099',
        ws: true
      }
    }
  }
})