PHP 当中有很多很有效的把戏变量, 比方__CLASS__
, __METHOD__
之类. 然则typescript中并没有. 因而我写了一个插件typescript-magic-variable-plugin
来运用它们, 源代码已放到了GitHub上: https://github.com/acrazing/t….
运用方法
- 起首你须要装置这个包:
npm install -D typescript-magic-variable-plugin
修正一下你的tsconfig:
{ "compilerOptions": { "plugins": [ { "transform": "typescript-magic-variable-plugin" } ] }, "include": [ // ... "./node_modules/typescript/magic-variable-plugin/types/globals.d.ts" ] }
在代码中运用把戏变量, 比方:
export class Foo { constructor() { console.log(__CLASS__) } }
- 用
ttypescript
来编译你的项目, 注重这里不能用typescript
, 由于没有开放transform
接口, 须要全局装置一下ttypescript
:npm i -g ttypescript
, 然后挪用ttsc
来编译.
进阶
也能够在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, {}) ] }) } } ]
现在支撑的变量:
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 能够自动给React的组件增添
displayName
属性, 默许开启, 比方:export class Foo extends Component {}
会自动给
Foo
增添静态属性:Foo.displayName = "Foo"
设置:
interface Options { addDisplayName: boolean; // 是不是给react组件增添displayName属性, 默许开启 rootDir: string; // __DIR__的相对路径, 默许为tscofnig.json中的rootDir或许当前文件夹 }