Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 228
stefan.at.wpf Avatar asked May 15 '21 09:05

stefan.at.wpf


People also ask

Does craco support react scripts 5?

Bookmark this question.

Why craco is used in react?

CRACO stands for Create-React-App Configuration Override. It is implemented as an easy way to override create-react-app configuration without mastering Webpack or ejecting.

How does create react app command work?

Create React App (CRA) is a tool to create single-page React applications that is officially supported by the React team. The script generates the required files and folders to start the React application and run it on the browser.


Video Answer


1 Answers

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;
like image 66
Alexandr Tovmach Avatar answered Nov 15 '22 08:11

Alexandr Tovmach