在TypeScript项目中像PHP一样运用把戏变量

PHP 当中有很多很有效的把戏变量, 比方__CLASS__, __METHOD__之类. 然则typescript中并没有. 因而我写了一个插件typescript-magic-variable-plugin来运用它们, 源代码已放到了GitHub上: https://github.com/acrazing/t….

运用方法

  1. 起首你须要装置这个包: npm install -D typescript-magic-variable-plugin
  2. 修正一下你的tsconfig:

    {
        "compilerOptions": {
            "plugins": [
                { "transform": "typescript-magic-variable-plugin" }
            ]
        },
        "include": [
            // ...
            "./node_modules/typescript/magic-variable-plugin/types/globals.d.ts"
        ]
    }
  3. 在代码中运用把戏变量, 比方:

    export class Foo {
        constructor() {
            console.log(__CLASS__)
        }
    }
  4. ttypescript来编译你的项目, 注重这里不能用typescript, 由于没有开放transform接口, 须要全局装置一下ttypescript: npm i -g ttypescript, 然后挪用ttsc来编译.

进阶

  1. 也能够在webpack中运用:

    const { createMagicVariableTransformer } = require('typescript-magic-variable-plugin')
    // ...
    rules: [
        {
            test: /\.tsx?$/,
            loader: 'awesome-typescript-loader',
            options: {
                // ... other loader's options
                getCustomTransformers: program => ({
                    before: [
                       createMagicVariableTransformer(program, {})
                    ]
                })
            }
        }
    ]
  2. 现在支撑的变量:

    nametypedescription
    __NAMESPACE__stringthe full name of the current namespace, use . to join the parents
    __CLASS__stringthe class name of the declaring class
    __METHOD__stringthe method name of the declaring method
    __FUNCTION__stringthe function name of the declaring function
    __DIR__stringthe current directory of the code
    __FILE__stringthe current file full name of the code
    __LINE__numberthe current line number
  3. 能够自动给React的组件增添displayName属性, 默许开启, 比方:

    export class Foo extends Component {}

    会自动给Foo增添静态属性: Foo.displayName = "Foo"

  4. 设置:

    interface Options {
        addDisplayName: boolean; // 是不是给react组件增添displayName属性, 默许开启
        rootDir: string; // __DIR__的相对路径, 默许为tscofnig.json中的rootDir或许当前文件夹
    }
    原文作者:acrazing
    原文地址: https://segmentfault.com/a/1190000016099493
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞