Suppose that:
dist
folder.dist
folderYour main.js
of the electron APP may looks like:
const win = new BrowserWindow({
title: '...'
})
win.loadURL(`file://${__dirname}/dist/index.html`)
By default, in the vite generated html, the resource links look like:
<link rel="icon" href="/favicon.ico">
<script type="module" crossorigin src="/assets/index-e285a7a0.js"></script>
<link rel="stylesheet" href="/assets/index-6119ebed.css">
Electron cannot find the resources starting with /
. For example, on Windows, Electron treat /assets/index-6119ebed.css
as C:\assets\index-6119ebed.css
which is definitely nonexistent.
Instead of absolute paths, we should use relative paths for resources.
Edit vite.config.js
, and update the base
option to ''
:
export default defineConfig({
base: '', // notice this line
plugins: [
vue()
]
})
Then run vite build
again, and the html links changed to this:
<link rel="icon" href="./favicon.ico">
<script type="module" crossorigin src="./assets/index-e285a7a0.js"></script>
<link rel="stylesheet" href="./assets/index-6119ebed.css">
Now resources use relative urls like ./assets/index-6119ebed.css
.
const router = createRouter({
history: createWebHashHistory(),
})
Use createWebHashHistory()
instead of createWebHistory(import.meta.env.BASE_URL)
. Otherwise, Electron cannot recognize the URL.
Lazy Loading Routes means something like:
const UserDetails = () => import('./views/UserDetails.vue')
const router = createRouter({
routes: [{ path: '/users/:id', component: UserDetails }],
})
Use the traditional way so that electron can work:
import UserDetails from './views/UserDetails'
const router = createRouter({
routes: [{ path: '/users/:id', component: UserDetails }],
})