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

求助:在Laravel+Inertia+React新项目中启用TypeScript的方法

Laravel Breeze + Inertia 启用 TypeScript 解决方案

一、补全 TypeScript 基础配置

  • 安装TypeScript及React类型依赖:
    npm install typescript @types/react @types/react-dom --save-dev
  • 生成TypeScript配置文件:
    npx tsc --init
  • 修改tsconfig.json核心配置项:
    • 将target设为ES2020
    • 将module设为ESNext
    • 将jsx设为react-jsx
    • 开启strict: true(推荐开启类型严格校验)
    • 确保include数组包含resources/js/**/*,exclude数组包含node_modules

二、适配 Inertia 的 TypeScript 后缀与配置

  1. 批量重命名现有文件:把resources/js/Pages下所有.jsx文件改成.tsx(比如Welcome.jsx→Welcome.tsx)
  2. 修改入口文件:将resources/js/app.jsx重命名为resources/js/app.tsx,可按需添加类型提示(比如给createInertiaApp的参数补充类型)
  3. 更新Vite配置:修改vite.config.js,确保支持.tsx后缀,同时更新入口文件路径:
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import react from '@vitejs/plugin-react';

export default defineConfig({
    plugins: [
        laravel({
            input: 'resources/js/app.tsx',
            refresh: true,
        }),
        react(),
    ],
    resolve: {
        extensions: ['.js', '.jsx', '.ts', '.tsx'],
    },
});
  1. 修正Blade模板引用:打开resources/views/app.blade.php,把Vite引用改为@vite('resources/js/app.tsx')

三、补充Breeze缺失的TypeScript类型支持

如果Breeze未自动生成TypeScript相关配置,手动添加:

  • 安装Node类型依赖(可选,处理Node环境相关类型):
    npm install @types/node --save-dev
  • 在resources/js下创建types目录,新建inertia.d.ts文件扩展Inertia类型:
import { PageProps } from '@inertiajs/react';

declare module '@inertiajs/react' {
    interface PageProps {
        // 可在此添加全局页面Props的类型,比如用户认证信息等
    }
}
  • 更新tsconfig.json的include数组,加入resources/js/types/**/*

四、验证配置有效性

运行npm run dev,如果终端无TypeScript编译错误,说明配置生效。之后新建页面直接使用.tsx后缀即可。

内容的提问来源于stack exchange,提问作者Tomas Lucena

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 09:40:21