바벨 프리셋, 웹팩과 함께 사용하기

버건디·2023년 4월 17일
0

웹팩,바벨

목록 보기
5/5

바벨은 여러 플러그인들을 모아둔 프리셋들을 제공하는데, 대표적으로

@babel/preset-env
@babel/preset-react
@babel/preset-typescript
@babel/preset-flow

이렇게 총 4가지가 있다.

- @babel/preset-env

ECMAScript2015+ 문법을 변환시켜주는 프리셋이다.

- babel.config.js

module.exports = {
  presets: ["@babel/preset-env"],
};
npx babel src/app.js

프리셋을 설정해주면 자동으로 코드를 변환해준다.

저 프리셋 안에는 여러 옵션들을 넣어줄 수 있다.

- target 옵션

targets 옵션을 넣어주면 특정 브라우저 버전을 지원하도록 지정해줄 수 있다.

- babel-config.js

module.exports = {
 presets: [
   [
     "@babel/preset-env",
     {
       targets: {
         chrome: "79",
       },
     },
   ],
 ],
};

이런식으로 targets에 해당 사용할 브라우저 환경과 그 환경의 버전을 적어주면 그 버전에 맞도록 코드가 변환된다.


- Polyfill

Promise, Object.assign, Array.from 등 이러한 문법들은 ES6에서 도입된 문법이므로 ES5로 트랜스파일링 된다고 해도 마땅히 대체될 문법이 존재하지 않는다. 하지만 ES5의 문법으로 구현은 할 수 있다.

Polyfill을 이용하면 이를 대체할수 있는데, 대표적으로 core-js가 있다.

module.exports = {
  presets: [
    [
      "@babel/preset-env",
      {
        targets: {
          chrome: "79",
          ie: "11",
        },
        useBuiltIns: "usage",
        corejs: {
          version: 3,
        },
      },
    ],
  ],
};

useBuiltIns 라는 옵션이 있는데, useBuiltIns는 preset-env의 폴리필 삽입 방식을 말한다.

여기서는 entry, false, usage 값이 있다.

entry 설정은 core-js/stable과 regenerator-runtime/runtime 모듈을 전역 스코프에 직접 삽입한 경우에만 가능하다.

import 'core-js/stable';
import 'regenerator-runtime/runtime';

...

이런식으로 직접 삽입해서 필요한 폴리필을 추가해줄 수 있다.

하지만 이렇게 되면 모든 폴리필을 추가하는 것이므로 빌드 결과물의 용량이 커진다.

usage 옵션을 사용하면 바벨에서 필요한 폴리필만 가져온다.


실무에서는 바벨만 사용하기 보다 웹팩과 함께 사용하는데, 웹팩의 babel-loader를 사용하여 통합해서 사용한다.

npm install -D core-js babel-loader

- webpack.config.js

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

module.exports = {
 mode: "development",
 entry: "./src/app.js",
 output: {
   filename: "main.js",
   path: path.resolve(__dirname, "dist"),
   assetModuleFilename: "images/[hash][ext][query]",
 },
 module: {
   rules: [
     {
       test: /\.css$/,
       use: ["style-loader", "css-loader"],
     },
     {
       test: /\.(jpeg|jpg|gif|svg)$/,
       type: "asset/resource",
     },
     {
       test: /\.png/,
       type: "asset/inline",
     },
     {
       test: /\.js$/,
       loader: "babel-loader",
       exclude: "/node_modules/",
     },
   ],
 },
 plugins: [
   new webpack.BannerPlugin({
     banner: `
     Build Date : ${new Date().toLocaleString()}
     Commit Version : ${childProcess.execSync("git rev-parse --short HEAD")}
     Author : ${childProcess.execSync("git config user.name")}
     `,
   }),
   new webpack.DefinePlugin({}),
   new HtmlWebpackPlugin({
     template: "./src/index.html",
   }),
 ],
};

core-js와 babel-loader 를 설치해준후에 babel-loader를 웹팩에서 설정해준후 build를 하면 정상적으로 빌드가 된다.

profile
https://brgndy.me/ 로 옮기는 중입니다 :)

0개의 댓글