Magic constants for TypeScript like it in PHP

PHP contains some useful magic constants just like __CLASS__, __METHOD__, __FUNCTION__, etc. But it is not supported in native TypeScript. Now there is a plugin for TypeScript to do that, which is called as typescript-magic-variable-plugin

At first, you need to install the package in your TypeScript project:

npm install -D typescript-magic-variable-plugin
# or var yarn
yarn add -D typescript-magic-variable-plugin

And then, update your tsconfig.json to invoke this plugin:

"compilerOptions": {
"plugins": [
{ "transform": "typescript-magic-variable-plugin" }
"include": [
// your files

Finally, you need to use ttypescript to compile your code with command line. Or add custom transformer for awesome-typescript-loader with 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, {})

This package support the following magic constants:

  • __CLASS__
  • __METHOD__
  • __FUNCTION__
  • __DIR__
  • __FILE__

and, could add displayName for react components.

You can get more detailed information on GitHub: acrazing/typescript-magic-variable-plugin.

Enjoy your life~