TIL: Typescrypt, React 프로젝트 webpack, babel 설정 - 220809

Lumpen·2022년 8월 8일
0

TIL

목록 보기
110/242
yarn add react react-dom
yarn add -D typescript @types/react @types/react-dom
tsc --init // create tsconfig.json
yarn add -D @babel/core @babel/preset-env @babel/preset-react @babel/preset-typescript
yarn add -D webpack webpack-cli webpack-dev-server html-webpack-plugin
yarn add -D babel-loader
yarn add @babel/plugin-transform-runtime

babel

바벨 설정

yarn add -D @babel/core @babel/preset-env @babel/preset-react @babel/preset-typescript

@babel/preset-env : ES5+ 를 변환할 때 사용한다.
@babel/preset-react : React 를 변환할 때 사용한다.
@babel/preset-typescript : Typescript 를 변환할 때 사용한다.
@babel/plugin-transform-runtime
babel-polyfill

// .babelrc
{
  "presets": [
    "@babel/preset-env",
    [
      "@babel/preset-react",
      {
        "runtime": "automatic"
      }
    ],
    "@babel/preset-typescript"
  ],
  "plugins": [
    [
      "@babel/plugin-transform-runtime",
      {
        "regenerator": true
      }
    ]
  ]
}

webpack

yarn add -D webpack webpack-cli webpack-dev-server html-webpack-plugin
yarn add -D babel-loader
const HtmlWebpackPlugin = require("html-webpack-plugin");
const path = require("path");
const webpack = require("webpack");
// const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer");
// BundleAnalyzer는 Bundle 최적화 용도로 사용

module.exports = {
  entry: `${path.resolve(__dirname, "../client/src")}/index.tsx`,
  module: {
    rules: [
      {
        test: /\.(ts|tsx|js|jsx)$/,
        use: "babel-loader",
        exclude: /node_modules/,
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: `${path.resolve(__dirname, "../client/src/public")}/index.html`,
    }),
    new webpack.ProvidePlugin({
      React: "react",
    }),
  ],
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "../client/src/"),
    },
    extensions: [".js", ".ts", ".jsx", ".tsx", ".css", ".json"],
  },
  mode: "development",
};

css loader

webpack은 따로 모듈을 설치해주지 않으면 css 파일 로드를 하지 못한다

yarn add -D css-loader style-loader
// webpack.config.json
// rules에 코드 추가

  {
    test: /\.css$/,
    use: ["style-loader", "css-loader"],
  },

웹팩 img/svg/font 설정

그냥 root 파일에서 이미지를 로드하면 에러 발생

declarations.d.ts 파일 생성 후

declare module "*.png";
declare module "*.svg";

*.d.ts 파일이란?

타입스크립트 선언 파일 d.ts 는 타입스크립트 코드의 타입 추론을 돕는 파일이다 예를 들어, 전역 변수로 선언한 변수를 특정 파일에서 import 구문 없이 사용하는 경우 해당 변수를 인식하지 못한다 그럴 때 아래와 같이 해당 변수를 선언해서 에러가 나지 않게 할 수 있다

declare module 
declare function
declare class
declare global
declare plugin
declare namespace
// webpack.config.json 
// rules에 아래 코드 추가

{
  test: /\.(?:ico|gif|png|jpg|jpeg)$/i,
  type: "asset/resource",
},
{
  test: /\.(woff(2)?|eot|ttf|otf|svg|)$/,
  type: "asset/inline",
}

tsconfig.json

{
  "compilerOptions": {
    "outDir": "./dist",
    "target": "es5",
    "module": "esnext",
    "jsx": "react-jsx",
    "noImplicitAny": true,
    "allowSyntheticDefaultImports": true,
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true
  },
  "include": ["src"]
}

src/public/index.html

<!DOCTYPE html>
<html lang="ko">
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
  <meta
    name="viewport"
    content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"
  />
  <head>
    <title>hi</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

src/index.tsx

import { createRoot } from "react-dom/client";
import App from "./App";

const container = document.getElementById("root");
const root = createRoot(container as Element);

root.render(<App />);

src/App.tsx

const App = () => {
  return <div>Hello</div>;
};
export default App;

참조1

참조2

profile
떠돌이 생활을 하는. 실업자는 아니지만, 부랑 생활을 하는

0개의 댓글