react typescript 얹기

Hyor·2022년 1월 1일
0
post-thumbnail

react-with-webpack 을 이용에 typescript 를 얹어보겠습니다.

프로젝트 구조

typescript 를 사용하기 위한 devDependency를 설치합니다.

$ yarn add @types/react @types/react-dom typescript ts-loader --dev

@types/react - typescript 용 react
@types/react-dom - typescript 용 react-dom
typescript - 애플리케이션 규모의 JavaScript 개발을 위한 언어입니다.
ts-loader - webpack에서 typescript 를 load하기 위해 사용합니다.

tsconfig.json 생성

$ touch tsconfig.json

tsconfig.json

{
  "compilerOptions": {
    "outDir": "./dist/",
    "noImplicitAny": true,
    "lib": ["esnext", "dom"],
    "module": "esnext",
    "target": "es5",
    "jsx": "react",
    "allowJs": true,
    "moduleResolution": "node",
    "baseUrl": "src",
    "allowSyntheticDefaultImports": true
  }
}

webpack.config.json

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  mode: "development",
  entry: {
    index: "./src/index.tsx",
  },
  devtool: "inline-source-map",
  devServer: {
    compress: true,
    port: 3000,
    historyApiFallback: true,
    open: true,
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: "public/index.html",
      favicon: "public/favicon.png",
    }),
  ],
  output: {
    filename: "js/[name].js",
    path: path.resolve(__dirname, "dist"),
    clean: true,
    publicPath: "/",
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        use: ["babel-loader"],
        exclude: /node_modules/,
      },
      {
        test: /\.tsx?$/,
        use: "ts-loader",
        exclude: /node_modules/,
      },
      {
        test: /\.css$/i,
        use: ["style-loader", "css-loader"],
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: "asset/resource",
      },
    ],
  },
  resolve: {
    extensions: [".jsx", ".js", ".tsx", ".ts"],
  },
};

tsconfig.json 으로 config 변경이 안될경우
Ctrl + Shuft + P 로 "TypeScript: Select TypeScript Version..." ->
"Use Workspace Version" 으로 변경한다.

Cannot find module './logo.svg' or its corresponding type declarations.ts(2307)
이런 error 가 나옵니다. webpack에서는 svg 등 코드로 되어있지않는 기타 assets 은 별도의 선언이 필요합니다.

cunstom.d.ts 를 생성하여 기타 assets 처리를 해줍니다.

touch custom.d.ts

custom.d.ts

declare module "*.svg" {
  const content: any;
  export default content;
}

typescript 를 적용했으니 component를 분리하여 테스트해봅니다.

App.tsx

import React from "react";
import logo from "./logo.svg";
import "./App.css";
import PTag from "./PTag";

function App(): JSX.Element {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        {/* <p>
          Edit <code>src/App.js</code> and save to reload.
        </p> */}
        <PTag first="Edit " code="src/App.tsx" last=" and save to reload." />
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

PTag.tsx 를 생성합니다.

cd src && touch PTag.tsx

PTag.tsx

import React from "react";

interface pTagProperty {
  first: string;
  code: string;
  last: string;
}

function PTag({ first, code, last }: pTagProperty): JSX.Element {
  return (
    <p>
      {first} <code>{code}</code> {last}
    </p>
  );
}

export default PTag;

github

잘못된 부분 지적환영입니다.

참고자료
https://yarnpkg.com/package/
https://webpack.js.org/guides/typescript/#importing-other-assets

profile
개발 노트

0개의 댓글