[TIL] 220831

먼지·2022년 8월 31일
0

TIL

목록 보기
24/57
post-thumbnail

플젝기록

삽질 잊지 않게 중간중간 정리! 더 자세히 알아봐야 하는 정보들은 따로 정리하기

vite react typescript

참고
https://tooo1.tistory.com/588
https://larainfo.com/blogs/install-setup-vite-react-typescript-tailwind-css-3
https://www.npmjs.com/package/cra-template-tailwindcss-typescript

npm create vite@latest

Need to install the following packages:
  create-vite@latest
Ok to proceed? (y) y
√ Project name: ... project-name
√ Select a framework: » react
√ Select a variant: » react-ts

cd project-name
npm install
npm run dev

src/App.tsx

import { useState } from 'react'
import reactLogo from './assets/react.svg'
import './App.css'

function App() {
  const [count, setCount] = useState(0)

  return (
    <div className="App">
      <div>
        <a href="https://vitejs.dev" target="_blank">
          <img src="/vite.svg" className="logo" alt="Vite logo" />
        </a>
        <a href="https://reactjs.org" target="_blank">
          <img src={reactLogo} className="logo react" alt="React logo" />
        </a>
      </div>
      <h1>Vite + React</h1>
      <div className="card">
        <button onClick={() => setCount((count) => count + 1)}>
          count is {count}
        </button>
        <p>
          Edit <code>src/App.tsx</code> and save to test HMR
        </p>
      </div>
      <p className="read-the-docs">
        Click on the Vite and React logos to learn more
      </p>
    </div>
  )
}

export default App

src/main.tsx

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './index.css';

ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + React + TS</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>

vite 정확히 뭔진 모르지만 가볍고 빠르다고 해서 냅다 설치했는데 겁나 빠르다. 👍

+ tailwind

https://tailwindcss.com/docs/guides/create-react-app

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

**tailwind.config.js

module.exports = {
  content: [
    "./src/**/*.{js,jsx,ts,tsx}",
  ],
  ... 
}

src/index.css

@tailwind base;
@tailwind components;
@tailwind utilities;

react-router-dom

https://www.npmjs.com/package/react-router-dom

npm i react-router-dom

React Router v6.3.0 공식문서 읽으시오
src/App.tsx

import { BrowserRouter, Route, Routes } from 'react-router-dom';
import Home from './pages/Home';

<BrowserRouter>
  <NavBar /> // ! navbar를 App 위에 올리면 에러
  <Routes>
    <Route path='/' element={<Home />} />
    <Route path='*' element={<Component />} />
  </Routes>
</BrowserRouter> 

react-helmet

npm i --save react-helmet

console error

https://ywtechit.tistory.com/174

useInput customhook - generic

input state의 onChange, setValue 등을 매번 useState로 선언하기 번거로워서 useInput 커스텀 훅을 만들었는데, 전에도 만들었찌만 그땐 string type의 값만 다뤘었는데 이번엔 bool 타입도 추가돼서 initialValue에 따라 set함수에 전달되는 value도 같은 type으로 하고 싶은데 any는 안 되고 string | boolean | number 이것도 안 돼서 generic을 거의 처음 적용해봤는데 일단은 작동한다..! generic 문법이 익숙하지 않아서 저게 맞게 작성한 건지눈 모르겟다

import { useState } from 'react';

function useInput<T>(initialValue: T) {
  const [value, setValue] = useState<T>(initialValue);
  const onChangeValue = (e: React.ChangeEvent<any>) => {
    setValue(e.target.value);
  };
  const onClearValue = () => setValue(initialValue);
  return {
    value,
    setValue: (newValue: T) => setValue(newValue),
    onChangeValue,
    onClearValue,
  };
}

export default useInput;

fetch headers type

...
    const headers: HeadersInit = new Headers();
    headers.set('Content-Type', 'application/json');
    headers.set('Access-Control-Allow-Origin', 'http://...');
    headers.set('Access-Control-Allow-Credentials', 'true');
    fetch(`url`, { headers })

// or

	// 이렇게 작성해도 typeError 없었음
    const headers = {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': 'http://...',
      'Access-Control-Allow-Credentials': 'true',
    };
    fetch(`uurl`, { headers })

vite process is not defined

https://github.com/vitejs/vite/issues/1973
vite.config.ts

import { defineConfig } from 'vite'
// ...
export default defineConfig({
  // ...
  define: {
    'process.env': {}
  }
})
profile
꾸준히 자유롭게 즐겁게

0개의 댓글