6

I want to use ts-nameof in my React app created with create-react-app. How can I do that without ejection? Hint: I also use craco, so a solution involving craco would be also fine for me.

Thanks!

stefan.at.kotlin
  • 15,347
  • 38
  • 147
  • 270

1 Answers1

6

It's possible to achieve with babel-macro called ts-nameof.macro without ejecting.

I've tested on fresh application generated with:

npx create-react-app temp --template typescript
# install macro dependecies
yarn add -D ts-nameof.macro
# or
# npm i --save-dev ts-nameof.macro

NOTE: if your react-scripts version lower than 2.0, you also need to install babel-plugin-macros as dev dependency.

Update App.tsx

import React from 'react';
import nameof from "ts-nameof.macro"; // import nameof
import logo from './logo.svg';

import './App.css';

function App() {
  console.log(nameof(window.alert)) // "alert"
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.tsx</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;
Alexandr Tovmach
  • 3,071
  • 1
  • 14
  • 31