<aside> 💡 webpack을 활용하여 Typescript와 React를 개발할 수 있는 환경 구축 (webpack, React, Typescript, emotion)

</aside>

webpack.common.js

프로덕션 환경과 개발 환경 파일 분리 ✅

프로덕션 환경과 개발 환경에서 공동으로 적용해야 하는 경우 분리된 파일 모두 수정을 해야 하므로 번거롭고 중간에 설정이 누락될 가능성이 있습니다. 이러한 문제를 webpack-merge 를 활용하여 공통 설정과 환경별 설정을 분리하여 해결할 수 있었습니다. 이를 통해 코드 누락이나 중복되는 코드도 없고, 환경별로 다른 설정들을 직관적으로 확인할 수 있습니다.

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

module.exports = {
  entry: "./src/index.tsx",
  output: {
    filename: "bundle.js",
    path: path.resolve(__dirname + "/dist"),
    clean: true,
  },
  resolve: {
    extensions: [".js", ".jsx", ".ts", ".tsx"],
    alias: {
      "@": path.resolve(__dirname, "./src"),
    },
  },
  module: {
    rules: [
      {
        test: /\\.html$/,
        use: [
          {
            loader: "html-loader",
          },
        ],
      },
      {
        test: /\\.(ts|tsx)$/,
        use: "ts-loader",
        exclude: /node_modules/,
      },
      {
        test: /\\.(png|jpe?g|gif|svg)$/i,
        use: [
          {
            loader: "file-loader",
            options: {
              name: "[path][name].[ext]",
            },
          },
        ],
      },
    ],
  },
  plugins: [
    new HTMLWebpackPlugin({
      template: "./index.html", // 읽을 파일명
      filename: "./index.html", // output으로 출력할 파일명
    }),
  ],
};

webpack.config.dev.js

const { merge } = require("webpack-merge");
const common = require("./webpack.config.common.js");

module.exports = merge(common, {
  mode: "development",
  devtool: "inline-source-map",
  devServer: {
    port: 3000,
  },
});

webpack.config.prod.js

const { merge } = require("webpack-merge");
const common = require("./webpack.config.common.js");

module.exports = merge(common, {
  mode: "production",
  devtool: "source-map",
});

tsconfig.json

target : 코드의 변환 대상 ECMAScript 버전을 최신 버전으로 지정

module : 최신 ECMAScript 버전 모듈 시스템을 타겟으로 컴파일

moduleResolution : TypeScript가 모듈을 해석하고 처리하는 방식 지정

outDir : 컴파일 된 js 파일이 생성되는 위치 지정

noImplicitAny : 암시적 any를 허용하지 않음

strict : 엄격하게 타입 검사

jsx : React 프로젝트에서 JSX를 사용하기 위해 필요

jsxImportSource : 새로운 JSX 변환 방식(React 17+)으로 css prop 사용하기 위해 필요

allowSyntheticDefaultImports : default export 가 없어도 import 허용

sourceMap : 디버깅 시 어떤 파일에서 에러났는지 추적 용이