ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • React/TypeScript - 절대경로 지정
    Language/React 2022. 8. 2. 15:23

     

    `~/` 에 대한 절대경로를 추가해 보자.

     

    0. typescript 추가

    # typescript 추가
      $ yarn add --dev typescript @types/node @types/react @types/react-dom @types/jest

     

    1. paths alias 설정

    $ yarn add --dev react-app-rewired customize-cra

     

    2. tsconfig.json

    {
      "extends": "./tsconfig.paths.json",
      "compilerOptions": {
        "target": "es5",
        "lib": [
          "dom",
          "dom.iterable",
          "esnext",      
        ],
        "allowJs": true,
        "skipLibCheck": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "module": "esnext",
        "moduleResolution": "Node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "noEmit": true,
        "jsx": "react",
        
        "outDir": "./dist/", // 아웃풋 될 경로
        "noImplicitAny": true, // 음.. 암시적 any 타입의 표현식 및 선언에서 오류를 발생시킬지?
      }
    }

     

    3. tsconfig.paths.json

    {
      "compilerOptions": {
        "baseUrl": ".",
        "paths": {
          "~/*": [
            "src/*"
          ]
        }
      }
    }

     

    4. config-overrides

    const { override, addWebpackAlias } = require('customize-cra');
    const path = require('path');
    
    module.exports = override(
      addWebpackAlias({
        '~': path.resolve(__dirname, 'src'),
      }),
    );

     

    5. 실행 스크립트 변경 (package.json)

    {
      ...
      
      "scripts": {
        "start": "set PORT=3000 && react-app-rewired start",
        "build": "react-app-rewired build",
        "test": "react-app-rewired test",
        "eject": "react-scripts eject"
      },
      
      ...
    }

     

    6. Test.js

    import React from 'react';
    
    class Test extends React.Component {
        render() {
            return (
                <React.Suspense>
                    <br/>
                    <br/>
                    <br/>
                    <div>test</div>
                    <br/>
                    <br/>
                    <br/>
                </React.Suspense>
            )
        }
    }
    
    export default Test;

     

    7. index.js -> index.tsx

    import React from 'react';
    import ReactDOM from 'react-dom';
    import './index.css';
    import App from '~/App';
    import reportWebVitals from './reportWebVitals';
    
    ReactDOM.render(
    <React.StrictMode>
        <App />
    </React.StrictMode>,
    document.getElementById('root')
    );
    
    reportWebVitals();

     

    8. App.js -> App.tsx

    import React from 'react';
    // import logo from './logo.svg';
    import './App.css';
    import Test from '~/views/components/Test'
    
    // const Title = ({ text }) => (
    const Title: React.FC<{ text: string }> = ({ text }) => (
      <h1>{text}</h1>
    )
    
    if (process.env.ONLY_DEV) {
      console.log('This is only test be better development');
    }
    
    
    function App() {
      return (
        <div className="App">
          <header className="App-header">
            <Test />
            <Title text="Hello World!!" />
            <h2>{process.env.API_URL}</h2>
    
            {/* <img src={logo} className="App-logo" alt="logo" /> */}
            <p>
              Edit <code>src/App.js</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;

     

    9. 확인

     

     

    참고) paths alias
    - 절대 경로를 사용하려면 tsconfig.json과 webpack의 설정을 건들여야 한다.
    단순하게 tsconfig.json의 paths 설정을 바꾸면 된다 생각했지만 React 실행시 강제적으로 paths 설정을 지워 버린다. (충격...)
    https://7stocks.tistory.com/127

    - React + TypeScript 환경에서 절대경로 사용하기
    https://velog.io/@hoo00nn/React-TypeScript-%ED%99%98%EA%B2%BD%EC%97%90%EC%84%9C-%EC%A0%88%EB%8C%80%EA%B2%BD%EB%A1%9C-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0

    - Alias solution for rewired create-react-app
    https://githubhot.com/repo/mryhchan/react-app-rewire-alias

    'Language > React' 카테고리의 다른 글

    React/redux & react-redux & redux-saga & etc  (0) 2022.08.04
    React/router & Layout  (0) 2022.08.04
    React/material-ui  (0) 2022.08.02
    React/JSX - 절대경로 지정  (0) 2022.08.02
    React/프로젝트 생성  (0) 2022.08.02

    댓글

Designed by Tistory.