在TypeScript項目中像PHP同樣使用魔術變量

PHP 當中有許多頗有用的魔術變量, 好比__CLASS__, __METHOD__之類. 可是typescript中並無. 所以我寫了一個插件typescript-magic-variable-plugin來使用它們, 源代碼已經放到了GitHub上: https://github.com/acrazing/t....node

使用方法

  1. 首先你須要安裝這個包: npm install -D typescript-magic-variable-plugin
  2. 修改一下你的tsconfig:react

    {
        "compilerOptions": {
            "plugins": [
                { "transform": "typescript-magic-variable-plugin" }
            ]
        },
        "include": [
            // ...
            "./node_modules/typescript/magic-variable-plugin/types/globals.d.ts"
        ]
    }
  3. 在代碼中使用魔術變量, 好比:webpack

    export class Foo {
        constructor() {
            console.log(__CLASS__)
        }
    }
  4. ttypescript來編譯你的項目, 注意這裏不能用typescript, 由於沒有開放transform接口, 須要全局安裝一下ttypescript: npm i -g ttypescript, 而後調用ttsc來編譯.

進階

  1. 也能夠在webpack中使用:git

    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. 目前支持的變量:github

    name type description
    __NAMESPACE__ string the full name of the current namespace, use . to join the parents
    __CLASS__ string the class name of the declaring class
    __METHOD__ string the method name of the declaring method
    __FUNCTION__ string the function name of the declaring function
    __DIR__ string the current directory of the code
    __FILE__ string the current file full name of the code
    __LINE__ number the current line number
  3. 能夠自動給React的組件添加displayName屬性, 默認開啓, 好比:web

    export class Foo extends Component {}

    會自動給Foo增長靜態屬性: Foo.displayName = "Foo"typescript

  4. 配置:npm

    interface Options {
        addDisplayName: boolean; // 是否給react組件添加displayName屬性, 默認開啓
        rootDir: string; // __DIR__的相對路徑, 默認爲tscofnig.json中的rootDir或者當前文件夾
    }
相關文章
相關標籤/搜索