在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
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞