When electron loads html built by Vite, resources like css and js are not found

Problem description

In my electron app, I use vue to build the UI layer. After finishing development, I run vite build to package the vue app into a static html. But, when electron loads the packaged html, the page does not work because resources like css and js are not found.

Cause of the problem

By default, in the html built by Vite, resources are linked like:

<script type="module" crossorigin src="/assets/index-fa2a084a.js"></script>
<link rel="stylesheet" href="/assets/index-37cd7934.css">

Notice the src and href attributes. They are both absolute paths which are prefixed by /.

When electron loads a local html file, the absolute link paths are recognized as file system paths. Of course, there's not a directory /assets in the file system.

Solution

Use relative paths instead of absolute paths so that electron can find the resources.

Edit vite.config.js like this:


import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  base: '',
  plugins: [vue()]
})

Now run vite build to package the vue app again, and the html links now looks like:

<script type="module" crossorigin src="./assets/index-fa2a084a.js"></script>
<link rel="stylesheet" href="./assets/index-37cd7934.css">

Finally, electron can successfully load the vite built html.

Posted on 2023-04-25