babel-plugin-ts-nameof

raw JSON →
4.2.1 verified Sat Apr 25 auth: no javascript

A Babel plugin (v4.2.1) that implements the `nameof` keyword for TypeScript, mimicking C# `nameof` to get the string name of a variable, property, type, or member. It transforms compile-time expressions into their string representations, enabling refactor-safe string usage. Stable, maintained, and designed for use with Babel's TypeScript support. Different from ts-nameof (TypeScript compiler transformer) as it integrates into Babel pipelines. Requires @types/ts-nameof for type declarations.

error Cannot find name 'nameof'.
cause TypeScript cannot resolve the global `nameof` type because @types/ts-nameof is not installed or not included in tsconfig.
fix
Run npm install @types/ts-nameof --save-dev and add "types": ["ts-nameof"] to compilerOptions in tsconfig.json.
error TypeError: nameof is not a function
cause Runtime error because the plugin is not applied. nameof is a compile-time construct, not a runtime function.
fix
Ensure Babel is configured with babel-plugin-ts-nameof in your build pipeline and that you are running the code through Babel.
error Error: Plugin 'ts-nameof' not found
cause Incorrect plugin name in Babel configuration.
fix
Use 'babel-plugin-ts-nameof' (full npm package name) in plugins array.
gotcha nameof() only works at compile time; it is not available in runtime JavaScript.
fix Use only in TypeScript source files processed by Babel with this plugin enabled.
gotcha The plugin requires Babel's TypeScript preset or TypeScript compilation; does not work with plain JavaScript.
fix Ensure @babel/preset-typescript or similar is configured.
deprecated Previous versions (v3.x) used a different import style for type declarations.
fix Upgrade to v4 and use @types/ts-nameof.
gotcha nameof() cannot be used in evaluated code (e.g., inside template literals that are not strings).
fix Assign the result of nameof() to a variable first and use that variable.
gotcha Does not support all TypeScript types; only named types, properties, and methods are supported.
fix Check the documentation for supported syntax. Unsupported patterns will produce a compile error.
npm install babel-plugin-ts-nameof
yarn add babel-plugin-ts-nameof
pnpm add babel-plugin-ts-nameof

Installs the plugin, configures Babel and TypeScript, then demonstrates compile-time nameof expressions for class, type, property, and member access.

// Install: npm install babel-plugin-ts-nameof @types/ts-nameof --save-dev
// .babelrc
{
  "plugins": ["babel-plugin-ts-nameof"]
}
// tsconfig.json (for type declarations)
{
  "compilerOptions": {
    "types": ["ts-nameof"]
  }
}
// Usage
class Person {
  firstName: string;
  lastName: string;
}
const name = 'firstName';
console.log(nameof(Person)); // "Person"
console.log(nameof<Person>()); // "Person"
console.log(nameof<Person>('firstName')); // "firstName"
console.log(nameof<Person>(p => p.lastName)); // "lastName"