You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Svelte+Electron应用导航异常问题求助

解决方案

1. 修复导航链接的Class语法错误

你的+layout.svelte中,每个<a>标签的class模板字符串存在语法错误,错误地把默认样式写进了三元运算符的true分支,导致生成的class属性无效。修正后的代码如下:

<div class="ml-10 flex items-baseline space-x-4">
  <a href="/"
    class={`rounded-md px-3 py-2 text-sm font-medium
      ${page.url.pathname === '/'
        ? 'bg-gray-900 text-white'
        : 'text-gray-300 hover:bg-gray-700 hover:text-white'
      }` }
  >Rechnungen</a>
  <a href="/bilanz"
    class={`rounded-md px-3 py-2 text-sm font-medium
      ${page.url.pathname === '/bilanz'
        ? 'bg-gray-900 text-white'
        : 'text-gray-300 hover:bg-gray-700 hover:text-white'
      }`}
  >Gesamtbilanz</a>
  <a href="/admin"
    class={`rounded-md px-3 py-2 text-sm font-medium
      ${page.url.pathname === '/admin'
        ? 'bg-gray-900 text-white'
        : 'text-gray-300 hover:bg-gray-700 hover:text-white'
      }` }
  >Admin</a>
</div>

2. 调整SvelteKit静态构建配置

为适配Electron的file://协议环境,修改svelte.config.js,添加trailingSlash配置确保路径正确:

import adapter from '@sveltejs/adapter-static';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';

/** @type {import('@sveltejs/kit').Config} */
const config = {
  preprocess: vitePreprocess(),

  kit: {
    adapter: adapter({
      pages: 'build',
      assets: 'build',
      precompress: false,
      strict: true,
      trailingSlash: 'always' // 强制每个页面生成index.html,适配file://路径规则
    }),
    paths: {
      base: '' // 保持为空,确保相对路径解析正确
    },
    appDir: 'app' // 明确指定app目录,避免路由混淆
  }
};

export default config;

3. 确保Electron主进程正确加载构建产物

检查你的Electron主进程代码(通常为main.js/main.ts),确保它加载的是build目录下的index.html:

const { app, BrowserWindow } = require('electron');
const path = require('path');

function createWindow() {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      contextIsolation: true,
      nodeIntegration: false,
      webSecurity: false // 临时禁用web安全用于测试,后续可根据需求开启
    }
  });

  // 加载build目录下的index.html,路径需匹配你的项目结构
  mainWindow.loadFile(path.join(__dirname, '../build/index.html'));

  mainWindow.webContents.openDevTools();
}

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow();
});

4. 验证路由功能

完成上述配置后,执行以下步骤验证:

  1. 重新构建SvelteKit项目:npm run build
  2. 重新启动Electron应用
  3. 点击导航链接测试页面跳转

此时导航应该可以正常工作,不会再出现加载本地资源的错误。

内容的提问来源于stack exchange,提问作者dennis_10-33

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 15:50:18