大家好,又见面了,我是你们的朋友全栈君。
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, {})
]
})
}
}
]- 目前支持的变量:

- 可以自动给React的组件添加
displayName属性, 默认开启, 比如:
export class Foo extends Component- 会自动给
Foo增加静态属性:Foo.displayName = "Foo" - 配置:
interface Options {
addDisplayName: boolean; // 是否给react组件添加displayName属性, 默认开启
rootDir: string; // __DIR__的相对路径, 默认为tscofnig.json中的rootDir或者当前文件夹
}发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/107352.html原文链接:https://javaforall.cn


