@7nohe/laravel-typegen

中文文档
0.6.1发布于 2024/07/22MITTypeScriptCommonJS近 30 天下载 6395

库允许您从 Laravel 代码中生成 TypeScript 类型 .

中文使用文档
文档目录15 节
  1. 目录
  2. 特征
  3. 支持的版本
  4. 安装
  5. 使用量
  6. Enum 支持
  7. Laravel Enum 支持
  8. 使用强键 route() ziggy 函数
  9. Laravel 有用类型
  10. 申请类型
  11. 可用选项
  12. 发展
  13. 设置示例项目
  14. 调试
  15. 许可证

Laravel 类型

目录

特征

  • 从 Laravel 模型生成类型
  • 支持关系表
  • 支持 Enum( 来自 PHP8.1)
  • 从 Laravel 表格请求生成类型
  • 生成 siggy (Routing) 的类型
  • 为 Laravel 提供有用的类型( 如 pagination等)

支持的版本

该库支持以下版本:

  • Laravel 9.x和10.x (英语)
  • 脚本 5.0 及以上类型

安装

$ npm install -D @7nohe/laravel-typegen

Laravel Typegen可能需要安装 doctrine/dbal 通过作曲器执行 php artisan model:show 内部命令.

$ composer require doctrine/dbal

使用量

编辑软件包.json

{
    "scripts": {
        "typegen": "laravel-typegen"
    },
}
$ npm run typegen

Enum 支持

我们也支持php8.1 enums.

<!-- app/Enums/GenderType.php -->
<?php

namespace App\Enums;

enum GenderType: string
{
    case Male = 'Male';
    case Female = 'Female';
    case Other = 'Other';
}

然后,将模型属性投入enums.

<!-- app/Models/User.php -->
<?php

namespace App\Models;
use App\Enums\GenderType;

class User extends Authenticatable
{
    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'gender'            => GenderType::class,
    ];
}

此库将生成以下类型 :

export type User = {
    id: number;
    name: string;
    email: string;
    gender: GenderType;
    email_verified_at?: string;
    created_at?: string;
    updated_at?: string;
    posts?: Post[];
};
export enum GenderType {
    Male = "Male",
    Female = "Female",
    Other = "Other"
}

Laravel Enum 支持

如果您使用 拉维尔·埃纳姆选项 --laravel-enum。 。 。 .

{
    "scripts": {
        "typegen": "laravel-typegen --laravel-enum"
    },
}

使用强键 route() ziggy 函数

运行 laravel-typegen 命令与 --ziggy 选项将生成路由.d.ts.

帮助输入 route() 函数.

{
    "scripts": {
        "typegen": "laravel-typegen --ziggy"
    },
}

例如,定义下列路线

// routes/web.php
Route::resource('posts', PostsController::class);
$ php artisan route:list
GET|HEAD posts/{post} posts.show › PostsController@show

参数将严格根据路由名称进行核对.

// in your TypeScript code

// OK
route('posts.show', { post: post.id })

// Error
route('posts.show', { id: post.id })

如果您创建了使用 --typescript laravel Breeze 的选项,您需要删除此选项的声明 route() 在资源/js/类型/global.d.ts中运行.

import { PageProps as InertiaPageProps } from '@inertiajs/core';
import { AxiosInstance } from 'axios';
 import ziggyRoute, { Config as ZiggyConfig } from 'ziggy-js';
import { PageProps as AppPageProps } from './';

declare global {
    interface Window {
        axios: AxiosInstance;
    }

    var route: typeof ziggyRoute;
    var Ziggy: ZiggyConfig;
}

- declare module 'vue' {
-     interface ComponentCustomProperties {
-        route: typeof ziggyRoute;
-     }
- }

declare module '@inertiajs/core' {
    interface PageProps extends InertiaPageProps, AppPageProps {}
}

Laravel 有用类型

我们为Laravel(特别是Inertia)提供了有用的类型.

例如,要返回 Dashboard Captain 中的 Pagized Inertia 响应, 您可以写到以下

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Inertia\Inertia;

class DashboardController extends Controller
{
    public function __invoke()
    {
        $users = User::latest('id')->paginate(5);
        return Inertia::render(
            'Dashboard',
            [
                'users' => $users
            ]
        );
    }
}

您可以导入 Laravel Typegen 已经定义的类型 .

<!-- Dashboard.vue -->
<script setup lang="ts">
import { Paginate } from '@7nohe/laravel-typegen';
import { User } from '@/types/model'; // generated types

defineProps<{ users: Paginate<User> }>();

</script>
<template>
    <div>
        <ul>
            <li v-for="user in users.data">- {{ user.name }}({{ user.email }})</li>
        </ul>
        <div class="flex justify-center mt-4 space-x-4">
            <Link v-for="(link, key) in users.links" :key="key" :href="link.url ?? '#'" v-html="link.label" />
        </div>
    </div>
</template>

申请类型

您可以通过执行命令从 Laravel 格式请求中生成类型 --form-requests 选项.

申请表格的类别如下:

<?php

namespace App\Http\Requests;

use App\Models\User;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class ProfileUpdateRequest extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules()
    {
        return [
            'name' => ['string', 'max:255'],
            'email' => ['email', 'max:255', Rule::unique(User::class)->ignore($this->user()->id)],
        ];
    }
}

相应的TypeScript类型将自动生成如下:

// formRequests.ts
export type ProfileUpdateRequest = {
    name?: string;
    email?: string;
};

通过与Axios等HTTP客户端库结合使用这些生成的类型,可以写出更多的类型安全代码.

可用选项

Usage: laravel-typegen [options]

Generate TypeScript types from your Laravel code

Options:
  -V, --version                output the version number
  -o, --output <value>         Output directory (default: "resources/js/types")
  --laravel-enum               Use Laravel Enum (default: false)
  --enum-path <value>          Path to enum files (default: "app/Enums")
  --model-path <value>         Path to model files (default: "app/Models")
  -z, --ziggy                  Generate types for ziggy (default: false)
  --vendor-routes              Include routes defined by vendor packages (default: false)
  --ignore-route-dts           Ignore generating route.d.ts (default: false)
  --form-request               Generate types for FormRequests (default: false)
  --form-request-path <value>  Path to FormRequest files (default: "app/Http/Requests")
  -h, --help                   display help for command

发展

设置示例项目

$ cd examples/laravel10-app
$ cp .env.example .env
$ docker run --rm \
    -u "$(id -u):$(id -g)" \
    -v "$(pwd):/var/www/html" \
    -w /var/www/html \
    laravelsail/php81-composer:latest \
    composer install --ignore-platform-reqs
$ ./vendor/bin/sail up -d
$ ./vendor/bin/sail php artisan key:generate
$ ./vendor/bin/sail php artisan migrate --seed
$ ./vendor/bin/sail npm install

调试

$ pnpm install
$ sh debug.sh

许可证

麻省理工学院

版本与发布记录

@7nohe/laravel-typegen 共发布 25 个版本,首次发布于 2022/11/21;过去 12 个月发布了 0 个版本。

版本发布日期距今
0.6.1latest2024/07/222 年前
0.6.02024/05/252 年前
0.5.42024/05/192 年前
0.5.32024/05/012 年前
0.5.22024/03/212 年前
0.5.12024/02/052 年前

关于 @7nohe/laravel-typegen 的常见问题

@7nohe/laravel-typegen 是什么?

库允许您从 Laravel 代码中生成 TypeScript 类型 .

如何安装 @7nohe/laravel-typegen?

在项目目录运行 npm install @7nohe/laravel-typegen,或使用 pnpm add / yarn add / bun add。它还提供命令行工具 laravel-typegen,可以用 npx laravel-typegen 直接运行。

@7nohe/laravel-typegen 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@7nohe/laravel-typegen 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@7nohe/laravel-typegen 可以商用吗?

@7nohe/laravel-typegen 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@7nohe/laravel-typegen 的下载量有多少?

根据 npm 官方下载统计,@7nohe/laravel-typegen 在 2026/10/05 – 2026/11/03 这 30 天内被下载 6,395 次,日均约 213 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@7nohe/laravel-typegen 还在维护吗?

最新版本 0.6.1 发布于 2024/07/22(2 年前);至今共发布 25 个版本,其中过去 12 个月发布了 0 个;首次发布于 2022/11/21。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。