How to use ts-nameof with create-react-app or craco?
Asked Answered
J

1

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!

Judson answered 15/5, 2021 at 9:4 Comment(0)
P
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;
Perth answered 24/5, 2021 at 10:10 Comment(3)
thank for this great reply, bounty awarded! btw, the linked babel-macro docs state that create-react-app already comes with babel-macro, can only confirm that - I didn't have to install it :-)Judson
I've added it to answer because wasn't sure about your react-scripts version. Yes, if you have higher than 2.0 you don't need that.Perth
Updated answer with note. Thanks 😌Perth

© 2022 - 2024 — McMap. All rights reserved.