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!
Bookmark this question.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With