Ts babel&wepack초기 환경 셋팅

YoonSam·2019년 11월 25일
1

typescript

목록 보기
1/1
post-thumbnail

시작하며

본 포스팅은 제가 타입스크립트를 처음 공부하면서 바벨이랑 웹팩
그리고 tsconfig.json 설정파일을 작성하면서 블로그에 기록해두고 보려고
작성하는 글입니다. 저한테 필요한 것들을 모아둔거라 여러분들한텐 필요없는
패키지나 코드가 있을 수 있습니다. (결론 : 두서가 없다는 뜻)

초기환경 셋팅하기

폴더 만들기

mkdir initial_ts_setting

package.json file 생성하기

 npm init -y

typescript 설치하기

npm i -g typescript

tsconfig.json 설정파일 생성하기
tsconfig.json파일을 생성하는 방법은 두가지 이다.
1) 직접 파일생성하여 작성하기
2) tsc --init 으로 자동 생성하기

{
  "compilerOptions": {
    "target": "es6",
    "module": "es6",
    "moduleResolution": "node",
    "declaration": false,
    "noImplicitAny": false,
    "jsx": "react",
    "sourceMap": true,
    "noLib": false,
    "suppressImplicitAnyIndexErrors": true
  },
  "compileOnSave": false,
  "exclude": ["node_modules"]
}

install

npm i @babel/cli @babel/core @babel/polyfill 
@babel/preset-env @types/react @types/react-dom 
awesome-typescript-loader babel-loader css-loader 
file-loader html-webpack-plugin mini-css-extract-plugin style-loader typescript url-loader webpack 
webpack-cli webpack-dev-server --save-dev

webpack 설정하기

html-webpack-plugin
기본적으로, bundle한 css, js파일들은
html파일에 직접 추가해야하는 번거로움이 있습니다.
html-webpack-plugin를 사용하면 이 과정을 자동화 할 수 있습니다.

mini-css-extract-plugin
CSS를 추출해서 파일로 저장하는 플러그인

extensions
extensions 에 넣은 확장자들은 웹팩에서 알아서 처리해주기 때문에
파일에 해당 확장자들을 입력할 필요가 없어집니다.

entry: ["@babel/polyfill", "./main.ts"]
entry는 웹팩이 빌드할 파일을 알려주는 역할을 합니다.

@babel/polyfill?
바벨을 사용하면 새로운 문법을 구형 자바스크립트 문법으로만 바꿔줍니다.
문법만 바꿔주면 됐지 뭘 더 바라냐고요?
바벨 그 자체로는 ES2015의 새로운 객체(Promise, Map, Set 등등)과 
메소드(Array.find, Object.assign 등등)을 사용할 수 없습니다.
왜냐하면 ES2015에서 처음 생긴 거라
구형 자바스크립트에는 그에 상응하는 코드가 없거든요.
그래서 babel-polyfill을 설치해야 새로운 기능을 사용할 수 있습니다.

output
output은 웹팩이 어디에 번들을 만들어 낼것인지,
어떤이름으로 파일들을 어떻게 만들것인지에 대해서 말해주는 곳 입니다.

filename: "bundle.js"
output안에서 filename은 번들링 돼서 나온 결과 파일을 말합니다.

devtool: "source-map"
devtool: "source-map" 옵션은 SourceMaps을 생성할지 말지를 결정하는 옵션입니다.
에러가 발생할 때, 어느 부분에서 에러가 발생했는지 알아야 디버깅이 수월할텐데요, 
source map은 bundle된 코드에서 발생한 에러를 기존의 코드와 연결시켜주는 역할을 합니다. 
devtool에서 설정할 수 있는 옵션들에는 여러 가지가 존재하며각각의 장단점이 존재합니다.

devServer
빠른 실시간 리로드 기능을 갖춘 개발 서버입니다.
디스크에 저장되지 않는 메모리 컴파일을 사용하기 때문에 컴파일 속도가 빨라집니다.
webpack.config.js에도 devServer 옵션을 통해 옵션을 지정하여 사용이 가능합니다.

exclude: /node_modules/
exclude는 제외할 폴더나 파일로, 바벨로 컴파일하지 않을 것들을 지정해줍니다.
바벨로는 컴파일하지 않지만 웹팩으로는 컴파일합니다.
반대로 include로 꼭 이 로더를 사용해서 컴파일할 것들을 지정해줄 수도 있습니다.

loader: "awesome-typescript-loader"
Typescript를 컴파일 시키는 방법으로는 3가지 정도의 방법이 있습니다.
1)ts-loader
2)awesome-typescript-loader
3)babel-loader에 typescript-preset를 얻는 방법
awesome-typescript-loader는 사용하는것을 지양하는 편이 좋다고 이야기들 합니다.

const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const path = require("path");

const basePath = __dirname;

module.exports = {
  context: path.join(basePath, "src"),
  resolve: {
    extensions: [".js", ".ts", ".tsx"]
  },
  entry: ["@babel/polyfill", "./index.tsx"],
  output: {
    path: path.join(basePath, "dist"),
    filename: "bundle.js"
  },
  devtool: "source-map",
  devServer: {
    contentBase: "./dist", // Content base
    inline: true, // Enable watch and live reload
    host: "localhost",
    port: 8080,
    stats: "errors-only"
  },
  module: {
    rules: [
      {
        test: /\.(ts|tsx)$/,
        exclude: /node_modules/,
        loader: "awesome-typescript-loader",
        options: {
          useBabel: true,
          babelCore: "@babel/core" // needed for Babel v7
        }
      },
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, "css-loader"]
      },
      {
        test: /\.(png|jpg|gif|svg)$/,
        loader: "file-loader",
        options: {
          name: "assets/img/[name].[ext]?[hash]"
        }
      }
    ]
  },
  plugins: [
    //Generate index.html in /dist => https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: "index.html", //Name of file in ./dist/
      template: "index.html", //Name of template in ./src
      hash: true
    }),
    new MiniCssExtractPlugin({
      filename: "[name].css",
      chunkFilename: "[id].css"
    })
  ]
};

참고용 링크

.babelrc

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "useBuiltIns": "entry"
      }
    ]
  ]
}

profile
안녕하세요~

0개의 댓글