연습장

04. ES6 -> @babel/polyfill 에서 core-js@3 본문

클론코딩해보기/환경 세팅

04. ES6 -> @babel/polyfill 에서 core-js@3

js0616 2024. 8. 12. 20:50

https://poiemaweb.com/babel-polyfill

 

폐지된 @babel/polyfill 대신 @babel/plugin-transform-runtime을 사용해 폴리필 추가하기 | PoiemaWeb

폐지된 @babel/polyfill 대신 @babel/plugin-transform-runtime을 사용해 폴리필 추가하기

poiemaweb.com

 

 

polyfill 은 ES6에서 추가된 Promise, Object.assign, Array.from 등은 ES5 이하로 트랜스파일링하여도 대체할 ES5 기능이 없기 때문에 그대로 남아 있기 때문에 사용했는데... 

 

Babel 7.4.0부터 @babel/polyfill은 deprecated 되었다. 즉 권장되지 않음.

 

이유로는 gpt 가 말하길.. 

@babel/polyfill은 모든 polyfill을 포함하여 전체적으로 무겁고 비효율적일 수 있습니다.

최신 권장 방식은 core-js와 regenerator-runtime을 사용하는데,

이는 필요한 polyfill만 선택적으로 포함할 수 있어 최적화된 번들 크기를 유지할 수 있기 때문입니다.

 

다른 곳에서는 

"전역 스코프가 오염될 경우, 고객 페이지에서 이름 충돌이 발생하고, 예측하기 힘든 에러가 발생할 수 있습니다. 기존 웹채팅에서는 바벨 폴리필(babel polyfill)이 전역 스코프에 삽입되어 전역 오염 이슈가 있었습니다."

https://tech.kakao.com/posts/412

 


-->  @babel/polyfill 대신 core-js 와 @babel/plugin-transform-runtime을 조합하여 사용

 

core-js : 최신 기능을 위한 polyfill을 제공

@babel/plugin-transform-runtime : 헬퍼 함수와 런타임 코드를 외부 모듈로 분리하여, 코드 중복을 줄이고 최적화

 

package.json

{
  "name": "es6_setting",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "build": "webpack -w"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": "",
  "devDependencies": {
    "@babel/cli": "^7.24.8",
    "@babel/core": "^7.25.2",
    "@babel/preset-env": "^7.25.3",
    "babel-loader": "^9.1.3",
    "css-loader": "^7.1.2",
    "mini-css-extract-plugin": "^2.9.0",
    "sass": "^1.77.8",
    "sass-loader": "^16.0.0",
    "style-loader": "^4.0.0",
    "webpack": "^5.93.0",
    "webpack-cli": "^5.1.4"
  },
  "dependencies": {
    "@babel/polyfill": "^7.12.1"
  }
}

 

설치되어있는 polyfill 을 삭제

npm uninstall @babel/polyfill

 

다음과 같이 설치

npm install core-js@3
npm install --save-dev @babel/plugin-transform-runtime
npm install @babel/runtime-corejs3

 

webpack.config.js 파일 수정

const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
    // enntry file
    // entry: './src/js/main.js',
    entry: ['./src/js/main.js', './src/sass/main.scss'],
    // 컴파일 + 번들링된 js 파일이 저장될 경로와 이름 지정
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'js/bundle.js'
    },
    plugins: [
        // 컴파일 + 번들링 CSS 파일이 저장될 경로와 이름 지정
        new MiniCssExtractPlugin({ filename: 'css/style.css' })
      ],
    module: {
        rules: [
        {
            test: /\.js$/,
            include: [
                path.resolve(__dirname, 'src/js')
            ],
            use: {
                loader: 'babel-loader',
                options: {
                    presets: ['@babel/preset-env'],
                    plugins: [
                        [
                          '@babel/plugin-transform-runtime',
                          {
                            // https://babeljs.io/docs/en/babel-plugin-transform-runtime#corejs
                            corejs: 3,
                            proposals: true,
                          },
                        ],
                      ],
                }
            },
            exclude: /node_modules/
        },
        {
            test: /\.scss$/,
            use: [
                MiniCssExtractPlugin.loader,
                "css-loader",   // translates CSS into CommonJS
                "sass-loader"   // compiles Sass to CSS, using Node Sass by default
            ],
            exclude: /node_modules/
          }        
        ]
    },
    devtool: 'source-map',
    mode: 'development'
};

 

npm run build 후 bundle.js 확인

다음과 같이 polyfill 이 필요한 코드가 뭔가 적용된 것을 알 수 있음 

 

 

'클론코딩해보기 > 환경 세팅' 카테고리의 다른 글

[최종] 바닐라 javaScript 세팅  (0) 2024.08.14
eslint + prettier 적용  (0) 2024.08.13
03. ES6 -> babel + Webpack + Sass  (0) 2024.08.12
02. ES6 -> babel + Webpack  (0) 2024.08.11
01. ES6 -> babel  (0) 2024.08.11