ReferenceError: window is not defined 怎么破tauri-nextjs-template 中调用 Tauri API 的正确姿势【免费下载链接】tauri-nextjs-templateA Tauri 2.0 Next.js (SSG) template, with TailwindCSS, opinionated linting, and GitHub Actions preconfigured项目地址: https://gitcode.com/gh_mirrors/ta/tauri-nextjs-template本文针对tauri-nextjs-templateTauri 2.0 Next.js 静态导出 SSG 桌面应用模板中常见的ReferenceError: window is not defined报错讲清原因并给出调用 Tauri API 的正确姿势帮你快速避开这个新手高频坑。为什么 Tauri Next.js 会报 window is not definedwindow is not defined几乎是每个 Tauri 2.0 Next.js 新手都会撞上的报错。它的本质是执行环境错位Next.js 开发服务器本质上是一个Node.js 服务器用于预渲染和热更新而 Node.js 环境里根本不存在window、navigator这些浏览器全局对象Tauri 的invoke、文件/窗口/系统 API 等底层依赖浏览器WebView环境才能工作一旦你在非客户端代码如服务端组件、全局工具模块里 import 了tauri-apps/api预渲染阶段就会立刻抛出ReferenceError: window is not defined。这个模板采用SSG静态生成方式构建next.config.ts中设置了output: export见 next.config.ts页面会在构建时被预先渲染这正是报错的高发场景。正确姿势把 Tauri API 留在客户端组件里修复思路只有一条让 Tauri 的 import 和执行都发生在浏览器环境。具体分两步第一步在客户端组件中导入给调用 Tauri API 的 React 组件加上use client指令并将invoke等 API 的 import 语句写在这个客户端组件文件内部而不是抽到全局工具文件里use client; import { invoke } from tauri-apps/api/core;模板示例页 src/app/page.tsx 正是这样写的组件顶部声明use client再导入invoke保证该模块只会在客户端加载。第二步在用户交互或运行时再执行更稳妥的做法是不要在组件顶层模块加载时就执行 Tauri 调用而是放到事件回调或useEffect中即“尽可能晚地执行”。模板首页按钮点击后才调用 Rust 函数就是这个模式const greet useCallback((): void { invokestring(greet).then((s) setGreeted(s)); }, []);对应的 Rust 端命令greet定义在 src-tauri/src/lib.rs注册进invoke_handler后即可被前端 invoke。快速上手3 步验证正确写法 想亲手跑一遍只需三步克隆并安装依赖pnpm 管理git clone https://gitcode.com/gh_mirrors/ta/tauri-nextjs-template cd tauri-nextjs-template pnpm install修改应用标识把 src-tauri/tauri.conf.json 中默认的com.tauri.dev改成你自己的 identifier否则 release 构建会失败。启动 Tauri 窗口执行pnpm tauri devNext.js 前端会直接在 Tauri WebView 中加载点击首页按钮即可看到 Rust 返回的 Hello world from Rust!。前端源码在src/src/app/layout.tsx、src/components/RoundedButton.tsx 等Rust 端源码在src-tauri/模板同时预配置了 TailwindCSS、Biome 格式化与 lint开箱即用。常见坑速查清单场景是否安全在use client组件内 importinvoke✅ 安全把tauri-apps/api抽到全局工具文件❌ 大概率报 window 未定义模块加载时组件顶层执行 invoke⚠️ 建议延后到交互/useEffect直接使用next/image默认优化❌ 模板已设unoptimized: true勿改回 一句话总结Tauri API 只在客户端、且尽量晚地调用window is not defined就再也不会出现。掌握这一点后配合模板的 SSG 构建与 lint 配置你就可以专注业务逻辑而不是和构建环境的差异打交道了。【免费下载链接】tauri-nextjs-templateA Tauri 2.0 Next.js (SSG) template, with TailwindCSS, opinionated linting, and GitHub Actions preconfigured项目地址: https://gitcode.com/gh_mirrors/ta/tauri-nextjs-template创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考