使用Typescript,Babel 7,装饰器保留元数据

dev*_*ull 9 babel typescript typeorm

我使用TypeORM与Babel 7和Typescript,似乎元数据不存在于编译的代码中.可以做些什么或者这是使用Babel的限制吗?

错误

ColumnTypeUndefinedError:Photo#isPublished的列类型未定义且无法猜到.确保在tsconfig.json中打开了"emitDecoratorMetadata":true选项.还要确保在应用程序的主条目文件之上导入了"reflect-metadata"(在导入任何实体之前).如果您使用的是JavaScript而不是TypeScript,则必须明确提供列类型.在新的ColumnTypeUndefinedError

Photo.js

import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm'

@Entity()
export class Photo {

    @PrimaryGeneratedColumn()
    id: number


    @Column()
    isPublished: boolean
}
Run Code Online (Sandbox Code Playgroud)

orm代码

import 'reflect-metadata'
import {createConnection} from 'typeorm'
import {Photo} from './entities/Photo'

createConnection({
    type: 'postgres',
    host: 'localhost',
    port: 5432,
    username: 'postgres',
    password: 'root',
    database: 'test',
    entities: [
        Photo
    ],
    synchronize: true,
    logging: false
}).then(connection => {
    // here you can start to work with your entities
}).catch(error => console.log(error))
Run Code Online (Sandbox Code Playgroud)

的package.json

{
    "name": "typescript-babel-node",
    "version": "0.1.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "dev": "run-p -r dev:run type-check:watch",
        "dev:run": "nodemon --exec babel-node --extensions '.ts,.js' src/index.js",
        "build": "babel src -d build --extensions '.ts,.js' src/index.js",
        "start": "node build/index.js",
        "type-check:watch": "tsc --watch",
        "test": "jest --watch"
    },
    "author": "",
    "license": "ISC",
    "dependencies": {
        "@types/node": "^10.12.0",
        "express": "^4.16.4",
        "pg": "^7.6.0",
        "ramda": "^0.25.0",
        "reflect-metadata": "^0.1.12",
        "typeorm": "^0.2.8"
    },
    "devDependencies": {
        "@babel/cli": "^7.1.2",
        "@babel/core": "^7.1.2",
        "@babel/node": "^7.0.0",
        "@babel/plugin-proposal-class-properties": "^7.1.0",
        "@babel/plugin-proposal-decorators": "^7.1.2",
        "@babel/plugin-proposal-object-rest-spread": "^7.0.0",
        "@babel/plugin-syntax-import-meta": "^7.0.0",
        "@babel/preset-env": "^7.1.0",
        "@babel/preset-typescript": "^7.1.0",
        "@types/express": "^4.16.0",
        "@types/jest": "^23.3.7",
        "@types/ramda": "^0.25.39",
        "babel-core": "^7.0.0-bridge.0",
        "babel-jest": "^23.6.0",
        "babel-plugin-module-resolver": "^3.1.1",
        "dot-env": "0.0.1",
        "eslint": "^5.7.0",
        "eslint-config-standard": "^12.0.0",
        "eslint-plugin-import": "^2.14.0",
        "eslint-plugin-node": "^7.0.1",
        "eslint-plugin-promise": "^4.0.1",
        "eslint-plugin-standard": "^4.0.0",
        "jest": "^23.6.0",
        "nodemon": "^1.18.5",
        "npm-run-all": "^4.1.3",
        "regenerator-runtime": "^0.12.1",
        "source-map-loader": "^0.2.4",
        "ts-jest": "^23.10.4",
        "typescript": "^3.1.3",
        "webpack": "^4.23.0",
        "webpack-cli": "^3.1.2"
    }
}
Run Code Online (Sandbox Code Playgroud)

Tit*_*mir 9

开箱即用,不支持,如另一个答案中所述.然而,我们可以编写一个babel插件来使其工作.

编写代码并不是很复杂,问题来自于我们在babel内部的信息的局限性.Babel不对打字稿执行类型检查.这意味着我们没有任何语义信息,我们只有类型注释以及我们可以从中获得哪些信息.这意味着我们的解决方案必然非常有限

限制:

  • 如果没有类型注释,我们没有要写的类型
  • 如果我们有类型引用,我们只能使用类型名称,我们无法检查refence是否是接口,类型别名,类或枚举.在实践中,这意味着:
    • 如果类型是接口或类型别名,则类型名称将undefined在运行时,以避免未定义我们可以执行type || Object以默认为对象,如果类型没有关联的运行时值
    • 如果类型是枚举,则Typescript将写入NumberString在元数据中,具体取决于枚举的类型.由于我们将类型名称写入元数据,这意味着您将最终得到元数据中枚举的容器对象.

类型序列化可以从typescript编译器本身复制,只需要很少的更改(它实际上只是两个函数serializeTypeNode,serializeTypeList大约有150行代码).

对于此示例类,我们得到的结果是:

declare var decorator: any;

interface ISampleInterface {

}

enum Flags { One }
class OtherClass {}


type ArrayAlias = number[]

class Test {
    @decorator
    untypedProp; // no design:type
    @decorator
    nrProp: number // Number as expected
    @decorator
    strProp: string // String as expected
    @decorator
    boolProp: boolean // Boolean as expected

    @decorator
    nrPropUndefined: number | undefined // Number as expected
    @decorator
    strPropUndefined: string | undefined // String as expected
    @decorator
    boolPropUndefined: boolean | undefined // Boolean as expected

    @decorator
    arrayProp: number[]

    // Type references
    @decorator
    classRefProp: OtherClass; // OtherClass || Object  = Object since OtherClass is still a class at runtime

    @decorator
    interfaceRefProp: ISampleInterface;  // ISampleInterface || Object  = Object since ISampleInterface is undefined at runtime

    @decorator
    enumRefProp: Flags; // Flags || Object = Flags since Flags exists as a value at runtime, here TS would have written Number/String

    @decorator
    typeAliasProp: ArrayAlias; // ArrayAlias || Object = Object since ArrayAlias does not exist t runtime and in Babel swe have no idea ArrayAlias is actually an array

    @decorator
    selfClassRefProp: Test; // Test || Object  = Object since Babel puts decorators instantiation before class definition, this is a quirk, this may be fixable
}
Run Code Online (Sandbox Code Playgroud)

实际的插件代码不是很大(减去从TS版本复制的方法):

export default declare((api: typeof import('@babel/core'), { jsxPragma = "React" }): PluginObj => {
  api.assertVersion(7);

  return {
    name: "transform-typescript-decorator-metadata",
    inherits: syntaxTypeScript,

    visitor: {
      ClassDeclaration(path) {
        var node = path.node;
        for (const field of node.body.body) {
          if (field.type !== "ClassProperty") continue;

          if (field.typeAnnotation && field.typeAnnotation.type === "TSTypeAnnotation" && field.decorators && field.decorators.length > 0) {
            const key = field.key as t.Identifier;
            const serializedType = serializeTypeNode(field.typeAnnotation.typeAnnotation);
            field.decorators.push(decorator(
              t.callExpression(
                t.memberExpression(t.identifier("Reflect"), t.identifier("metadata")), [
                  t.stringLiteral("design:type"),
                  t.logicalExpression("||", serializedType, createIdentifier("Object"))
                ])
            ))
          }
        }
      },
    }
  };
});
Run Code Online (Sandbox Code Playgroud)

您可以在此处找到完整的插件代码和工作示例

只是作为一个方面,插件排序很重要,如果@babel/plugin-proposal-class-properties在我们的插件之前,它将删除所有属性,我们的插件将不再有信息发出装饰器了.这是.babelrc我测试过并且它可以工作,我没有得到它与任何其他配置(但我不能说我努力尝试)

  {
    "env": {},
    "ignore": [],
    "plugins": [
      "../plugin/plugin.js",
      ["@babel/plugin-proposal-decorators", { "legacy": true }],
      ["@babel/plugin-proposal-class-properties", { "loose": true }],
      "babel-plugin-transform-es2015-modules-commonjs"
    ],
    "presets": [
      "@babel/preset-typescript"
    ]
  }
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的出色回答!从您的想法开始,我也开发了一个插件,尝试填补空白(使用`typeof`,因为如果启用了strict,则`Type || Object`是不安全的,添加参数修饰符,确保不会删除import语句)。在这里您可以找到[babel插件](https://github.com/leonardfactory/babel-plugin-transform-typescript-metadata) (4认同)

Gus*_*gel 6

不幸的是,我有理由确信这是在 Typescript 中使用 Babel 的限制。Babel 所做的是简单地去除 Typescript 类型,然后将代码视为 JavaScript。这意味着 babel 根本不关心您tsconfig.json ,因此也不关心emitDecoratorMetadata

所以不幸的是,如果你需要装饰器元数据,你必须坚持使用 tsc