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

Laravel Jetstream(Inertia/Vue)能否用TypeScript?及JS转TS方案咨询

Laravel Jetstream + Inertia/Vue 配置 TypeScript 方案

一、安装阶段手动配置 TypeScript

Jetstream 官方并未提供 TypeScript 的一键安装选项,但可以通过手动调整实现:

  1. 正常安装 Jetstream + Inertia/Vue
    先按照官方文档完成基础安装:

    composer require laravel/jetstream
    php artisan jetstream:install inertia
    npm install && npm run dev
    
  2. 安装 TypeScript 相关依赖
    执行命令安装所需依赖:

    npm install typescript vue-tsc @vitejs/plugin-vue @types/node --save-dev
    
  3. 创建并配置 tsconfig.json
    在项目根目录新建 tsconfig.json,示例配置如下:

    {
      "compilerOptions": {
        "target": "ESNext",
        "useDefineForClassFields": true,
        "module": "ESNext",
        "moduleResolution": "Node",
        "strict": true,
        "jsx": "preserve",
        "sourceMap": true,
        "resolveJsonModule": true,
        "isolatedModules": true,
        "esModuleInterop": true,
        "lib": ["ESNext", "DOM"],
        "skipLibCheck": true,
        "types": ["node"]
      },
      "include": ["resources/**/*.ts", "resources/**/*.d.ts", "resources/**/*.vue"],
      "references": [{ "path": "./tsconfig.node.json" }]
    }
    

    同时新建 tsconfig.node.json 用于 Vite 配置:

    {
      "compilerOptions": {
        "composite": true,
        "module": "ESNext",
        "moduleResolution": "Node",
        "allowSyntheticDefaultImports": true
      },
      "include": ["vite.config.ts"]
    }
    
  4. 调整 Vite 配置
    将 vite.config.js 重命名为 vite.config.ts,并更新内容:

    import { defineConfig } from 'vite';
    import laravel from 'laravel-vite-plugin';
    import vue from '@vitejs/plugin-vue';
    
    export default defineConfig({
      plugins: [
        laravel({
          input: 'resources/js/app.ts',
          refresh: true,
        }),
        vue({
          template: {
            transformAssetUrls: {
              base: null,
              includeAbsolute: false,
            },
          },
        }),
      ],
    });
    
  5. 更新入口文件与模板引用
    将 resources/js/app.js 重命名为 app.ts,并修改内容以适配 TypeScript:

    import { createApp, h } from 'vue';
    import { createInertiaApp } from '@inertiajs/vue3';
    import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';
    import { ZiggyVue } from '../../vendor/tightenco/ziggy/dist/vue.m';
    
    const appName = window.document.getElementsByTagName('title')[0]?.innerText || 'Laravel';
    
    createInertiaApp({
      title: (title) => `${title} - ${appName}`,
      resolve: (name) => resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob('./Pages/**/*.vue')),
      setup({ el, App, props, plugin }) {
        return createApp({ render: () => h(App, props) })
          .use(plugin)
          .use(ZiggyVue)
          .mount(el);
      },
      progress: {
        color: '#4B5563',
      },
    });
    

    最后修改 resources/views/app.blade.php 中的 Vite 引用路径为 app.ts。

二、现有 JS 文件转换为 TS 的规范步骤

如果已经完成 Jetstream 安装,可按以下步骤批量转换:

  • 批量重命名(逐步推进)
    不要一次性将所有 .js 文件改为 .ts,建议按模块拆分(比如先转换 Auth 相关组件,再处理其他页面),避免一次性出现大量类型错误。

  • 组件类型补全
    所有 Vue 组件需用 defineComponent 包裹,让 TypeScript 识别组件选项类型:

    import { defineComponent } from 'vue';
    
    export default defineComponent({
      props: {
        user: {
          type: Object as () => User,
          required: true,
        },
      },
      // ...其他组件逻辑
    });
    

    可提前定义接口(比如 User)来规范数据结构。

  • 类型注解补充
    为函数参数、返回值、变量添加明确的类型注解,消除隐式 any 错误:

    // 原 JS 代码
    function formatDate(date) {
      return new Date(date).toLocaleDateString();
    }
    
    // 转换为 TS
    function formatDate(date: string | Date): string {
      return new Date(date).toLocaleDateString();
    }
    
  • 修复类型错误
    利用 VS Code 等 IDE 的 TypeScript 提示,逐个修复类型不匹配、未定义变量等错误。对于暂时无法确定的类型,可先用 unknown 替代(不建议滥用 any)。

  • 配置 TypeScript 检查
    在 package.json 中添加脚本,方便批量检查类型:

    "scripts": {
      "type-check": "vue-tsc --noEmit"
    }
    

    执行 npm run type-check 可扫描所有 TS 文件的类型问题。

内容的提问来源于stack exchange,提问作者Ubeydullah Keleş

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 11:56:16