irontec/typescript-generator-bundle

基于Symfony项目生成TypeScript元素的包

安装: 4,204

依赖项: 0

建议者: 0

安全性: 0

星标: 2

关注者: 15

分支: 8

开放问题: 0

类型:symfony-bundle

0.2.3 2024-09-17 10:58 UTC

This package is auto-updated.

Last update: 2024-09-17 11:04:03 UTC


README

此包生成用于TypeScript的补丁,基于symfony项目。

安装

composer require irontec/typescript-generator-bundle

PHP >=7.4

命令

生成接口 生成包 生成所有

生成接口

此功能包括创建基于PHP类(设计为作为doctrine实体)的TypeScript接口。

这些接口会考虑这些类的属性。因此,有三种方法可以获取每个属性的类型。

  • PHP 7.4及以后版本中强类型定义的属性类型
    • private int $id;

  • 在属性注释中定义属性类型
    • @var int

  • 在doctrine注释中定义属性类型
    • @ORM\Column(type="integer")

如果找不到类型,将生成类型为"unknown"的接口。

通过执行以下命令生成接口

bin/console typescript:generate:interface output-dir [entities-dir]

此命令接受两个参数,其中一个为必需,另一个为可选。

output-dir [必需]: 创建接口的目录 entities-dir [可选]: 生成接口所使用的实体目录。默认为"src/Entity/"

要将实体转换为接口,需要在类的定义中写上注释"#TypeScriptMe",例如

<?php
namespace App\Entity;

...

/**
 * #TypeScriptMe
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 */
class User
{

...

在TypeScript中的类型定义

支持的类型列表

如果使用了dotrine注解并且定义了"nullable=true"或在属性强类型定义中类型前有",",则在属性名称后应用",",表示该参数为可选。

示例

PHP实体及其注解

// src/Entity/User.php
<?php

namespace App\Entity;

/**
 * #TypeScriptMe
 * @ORM\Table(name="user")
 */
class User
{

   /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     * @var int
     */
    private int $id;

    /**
     * @ORM\Column(type="string", length=100)
     * @var string
     */
    private $name;

    /**
     * @ORM\Column(type="string", length=100, nullable=true)
     */
    private $lastname;

    /**
     * @ORM\OneToMany(targetEntity="Factory", mappedBy="author")
     */
    private \Doctrine\Common\Collections\Collection $factories;

    /**
     * @ORM\OneToOne(targetEntity="Photo", mappedBy="user")
     */
    private $photo;

....

生成的TypeScript接口

// interfaces/User.ts

export interface User {
  id: number,
  name: string,
  lastname?: string,
  enabled: boolean,
  photo: Photo,
  factories: Factory[]
}

为了方便使用接口,生成了名为"models.d.ts"的文件,在其中导出所有接口。

// interfaces/models.d.ts

export * from './User';
export * from './Photo';
export * from './Factory';

生成包

bin/console typescript:generate:package output-dir [package-name] [version]

此命令生成一个包含基本数据的package.json文件,用于在npm私有仓库中发布。

每次运行包生成器时,默认会更新"Patch"版本,可以选择指定版本或升级到"patch"、"minor"或"major"版本。

生成的package.json示例

// interfaces/package.json
{
    "name": "@irontec/example",
    "version": "0.0.1",
    "description": "typescript interfaces for @irontec/example project",
    "types": "models.d.ts",
    "keywords": [],
    "author": "",
    "license": "EUPL"
}

管理版本号的库

生成所有

bin/console typescript:generate:all output-dir [entities-dir] [package-name] [version]

执行上述命令。

在NPM私有仓库中发布

要在私有仓库中发布,需要先生成package.json文件,并安装npm

  1. 在NPM中登录
npm adduser --registry https://npm.example.com
  1. 发布/更新接口更改
npm publish --registry https://npm.example.com