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或者当前文件夹 }