PHP 當中有許多頗有用的魔術變量, 好比__CLASS__
, __METHOD__
之類. 可是typescript中並無. 所以我寫了一個插件typescript-magic-variable-plugin
來使用它們, 源代碼已經放到了GitHub上: https://github.com/acrazing/t....node
npm install -D typescript-magic-variable-plugin
修改一下你的tsconfig:react
{ "compilerOptions": { "plugins": [ { "transform": "typescript-magic-variable-plugin" } ] }, "include": [ // ... "./node_modules/typescript/magic-variable-plugin/types/globals.d.ts" ] }
在代碼中使用魔術變量, 好比:webpack
export class Foo { constructor() { console.log(__CLASS__) } }
ttypescript
來編譯你的項目, 注意這裏不能用typescript
, 由於沒有開放transform
接口, 須要全局安裝一下ttypescript
: npm i -g ttypescript
, 而後調用ttsc
來編譯.也能夠在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, {}) ] }) } } ]
目前支持的變量: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 |
能夠自動給React的組件添加displayName
屬性, 默認開啓, 好比:web
export class Foo extends Component {}
會自動給Foo
增長靜態屬性: Foo.displayName = "Foo"
typescript
配置:npm
interface Options { addDisplayName: boolean; // 是否給react組件添加displayName屬性, 默認開啓 rootDir: string; // __DIR__的相對路徑, 默認爲tscofnig.json中的rootDir或者當前文件夾 }