Giter Site home page Giter Site logo

components's People

Contributors

pinkdumbbel avatar

Watchers

 avatar

components's Issues

프론트엔드 환경 설정

🔥 webpack 설정

직접 설정한 이유

CRA(create-react-app) or CNA(create-next-app)의 경우 사용하지 않는 기능 까지 설정되어 있어 모듈의 크기가 커지는 단점이 있고 CRA뿐만 아니라 여러 빌드 도구들도 있지만 가장 대표적인 빌드도구인 웹팩에 대한 이해와 학습을 위해 최소한의 설정으로 직접 개발환경을 셋팅 해보기로 하였습니다.


설치한 패키지

  • webpack: 웹상의 자원을 하나의 파일로 번들링 해주는 라이브러리
  • webpack-cli: 웹팩을 커맨드 명령어로 실행 할 수 있게 해주는 라이브러리
  • webpack-dev-server: 로컬 환경에서 개발서버를 실행 할 수 있게 해주는 라이브러리
  • babel-loader: 웹팩에서 바벨의 기능을 사용할 수 있게 해주는 라이브러리
  • @babel/cli: 커맨드 명령어를 이용하여 바벨을 통해 트랜스파일링 하기 위한 라이브러리
  • @babel/core: 바벨을 사용하여 트랜스파일링 하기 위한 필수 라이브러리
  • @babel/preset-env: 최신 자바스크립트 문법을 구버전의 자바스크립트 문법으로 트랜스파일링 해주는 라이브러리
  • @babel/preset-react: 리액트 문법을 자바스크립트 문법으로 트랜스파일링 해주는 라이브러리(ex. jsx문법 -> createElement함수로 변환)
  • @babel/preset-typescript: 타입스크립트 문법을 자바스크립트 문법으로 트랜스파일링 해주는 라이브러리
  • core-js: 기존 바벨 폴리필의 전역공간의 오염 문제와 바벨 런타임 인스턴스 문제를 해결한 런타임 폴리필 라이브러리
  • html-webpack-plugin: 웹팩 빌드시 html파일을 자동으로 생성해주는 라이브러리

설정파일 내용

webpack.config.js

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

module.exports = {
  mode: 'development',
  //번들링 하기 위한 시작점이 되는 파일
  entry: `${path.resolve(__dirname, './src')}/index.tsx`,
  resolve: {
    extensions: ['.js', '.jsx', '.ts', '.tsx', '.json'], //module import시 확장자 안붙여도 가능하도록 해주는 옵션
    alias: {
      '@': path.resolve(__dirname, 'src/'),
    },
  },
/*
loader - 웹팩이 웹 애플리케이션을 해석할 때 순수 자바스크립트 파일이 아닌 웹 자원(HTML, CSS, Images, 폰트 등)들을 
변환할 수 있도록 도와주는 속성
*/
  module: {
    rules: [
      {
        test: /\.(ts|tsx|js|jsx)$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
      },
    ],
  },
  plugins: [
    // public/index.html을 기본 템플릿 삼아 빌드시 빌드된 자바스크립트 파일이 삽입된 html 자동생성
    new HtmlWebpackPlugin({
      template: `${path.resolve(__dirname, './public')}/index.html`,
      inject: 'body',
    }),
    //각 모듈마다 import React from 'react'자동 삽입
    new webpack.ProvidePlugin({
      React: 'react',
    }),
  ],

  /* 
  output: entry로 시작된 파일이 loader를 거쳐 하나의 번들링된 파일로 생성
  publicPath: devServer실행시 router와 같은 역할을 함 
  즉 publicPath로 설정된 경로 ex) http://localhost.com:3000/${publicPath}
  로 접근 해야 비로소 화면이 보여진다 
  */
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].js',
    publicPath: '/',
    clean: true,
  },
  stats: {
    children: true,
  },
  devServer: {
    open: true, // devServer 실행시 자동으로 브라우저 실행하여 화면 출력
    hot: true, // 기본적으로 전체 리로드 되지만 react와 같은 spa의 경우 전체 리로드 될 경우 데이터가 사라지는 문제 발생 따라서 모듈별로 리로드
    compress: true, // 압축
    port: 3000,
    historyApiFallback: true, //라우터 이동시 (Link) 새로고침을 하게되면 브라우저상에 적혀있는 url주소는 실제 서버 주소가 아님에도 불구하고 리로드 되게 할 수 있는 기능
    liveReload: true,
  },
};

.babelrc

  • 바벨의 설정파일로 따로 분리하지 않을경우 웹팩 바벨로더 options로 직접 설정 해줘야함
{
  "presets": [
    "@babel/preset-react",
    [
      "@babel/preset-env",
      {
        "modules": false,
        "useBuiltIns": "usage",
        "corejs": 3
      }
    ],
    "@babel/preset-typescript"
  ]
}

.tsconfig.json

{
  "compilerOptions": {
    "outDir": "./dist", //컴파일된 파일이 저장되는 디렉토리명
    "target": "es5", //컴파일시 적용되는 자바스크립트 버전
    "module": "esnext", //어떤 모듈문법을 사용 할지 ex).import, required
    "jsx": "react-jsx", //tsx 확장자에 대한 컴파일 출력 형식 지정
    "noImplicitAny": true, //타입 추론이 어려울 경우 명시적으로 any라도 설정 해야 됨
    "allowSyntheticDefaultImports": true, //불러오려는 모듈에 export default가 없어도 import deafault 할수 있게 해주는 옵션
    "lib": ["dom", "dom.iterable", "esnext"], //컴파일 과정에 사용될 라이브러리 파일 설정
    "allowJs": true, //자바스크립트 파일 컴파일 허용
    "strict": true, //typescript의 type검사 옵션중 strict* 관련된 모든 것을 true로 변경
    "forceConsistentCasingInFileNames": true, // 파일명에 대소문자 구분하지 않아도 되는 기능 사용 여부
    "moduleResolution": "node", // 모듈 (검색)해석 방식 설정
    "isolatedModules": true, //각 파일을 분리된 모듈로 트랜스파일
    "baseUrl": "./", // Non-relativ 모듈 혹은 paths 옵션의 기준 디렉토리
    "resolveJsonModule": true, // 타입스크립트에서 json모듈 import 되도록 허용
    "paths": {
      // baseUrl 옵션을 기준디렉토리로 불러올 모듈의 위치 설정이 가능
      "@/*": ["src/*"]
    }
  },
  "include": ["src"]
}

참고 자료

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.