서버/Webpack

Webpack - ecmascript 최신 내용 적용 안될 때 babel을 추가하여 빌드하기

탐훈 2024. 11. 5. 12:24
728x90

ECMAScript는 계속해서 업데이트 된다. 

browser는 업데이트된 속도를 따라가지 못한다.

 

개발자들은 기다릴 필요 없이 

새로나온 ECMAScript 기능을 old 버전으로 바꿔주면 된다.

 

바꿔주는 녀석이 babel이다. 

 

all browser can understand 


 

 

1. 바벨 관련 패키지 추가

npm install @babel/core babel-loader @babel/preset-env @babel/plugin-proposal-class-properties --save-dev

 

2. webpack.config.js

// can't use ecma script module. use only common.js
console.log("module >>> ", module);
const path = require('path');

// minimum option
module.exports = {
    entry: './src/index.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, './dist'),
        /**
         * publicPath
         * under version 4: publicPath is empty('').
         * over version 4: publicPath is auto
         * 
         * can use list
         *      1. 'dist/'
         *      2. 'https://image.oliveyoung.co.kr/uploads/contents/202410/25oyDay/pc_visual.jpg'
         */
        publicPath: 'dist/'
    },
    mode: 'none',
    module: {
        /**
         * webpack: I don't know what that menas 'import Kiwi...'
         * me: thank you for asking, If you don't know somethig, you should check out the rules.
         * webpack: perfect
         */
        rules: [
            {
                test: /\.(png|jpg)$/,
                /**
                 * asset/inline  :bake image into base64. could be larger file size(more better)
                 * asset/resource: request image each of them. cost of call is larger
                 */
                type: 'asset',
                parser: {
                    dataUrlCondition: {
                        maxSize: 3 * 1024 // 3kilobyte
                    }
                }
            },
            {
                test: /\.txt$/,
                type: 'asset/source'
            },
            {
                // loader should be installed explicitly
                test: /\.css$/,
                use: [
                    'style-loader', 'css-loader'
                ]
            },
            {
                test: /\.scss$/,
                // webpack invoke right to left in array
                // 
                use: [
                    'style-loader', 'css-loader', 'sass-loader'
                ]
            },
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        // ecmascript 8 to 5 (4;55)
                        presets: ['@babel/env'],
                        plugins: ['@babel/plugin-proposal-class-properties']
                    }
                }
            }
        ]
    }
}

 

3. index.js

import HelloWorldButton from "./components/hello-world-button";

const helloWorldButton = new HelloWorldButton();
helloWorldButton.render();

 

4. hello-world-button.js

import './hello-world-button.scss'

class HelloWorldButton {
    buttonCssClass = 'hello-world-text2'; // *** new browser cannot understand
    
    render() {
        const button = document.createElement('button');
        button.innerHTML = 'Hello World';
        // button.classList.add('hello-world-text'); // *** old version
        button.classList.add(this.buttonCssClass);   // *** new browser cannot understand
        button.onclick = function() {
            const p = document.createElement('p');
            p.innerHTML = 'Hello World';
            p.classList.add('hello-world-text'); 
            body.appendChild(p);
        }
        const body = document.querySelector('body');
        body.appendChild(button);
    }
}

export default HelloWorldButton;

 

5. hello-world.button.scss

$font-size: 20px;
$button-background-color: green;
$button-font-color: white;
$text-font-color: red;

.hello-world-button {
    font-size: $font-size;
    padding: 7px 15px;
    background: $button-background-color;
    color: $button-font-color;
    outline: none;
}

.hello-world-text2 {
    color: $text-font-color;
    font-weight: bold;
}

 

6. package.json

{
  "scripts": {
    "build": "webpack"
  },
  "devDependencies": {
    "sass": "^1.80.6",
    "sass-loader": "^16.0.3",
    "webpack": "^5.95.0",
    "webpack-cli": "^5.1.4"
  },
  "dependencies": {
    "css-loader": "^7.1.2",
    "style-loader": "^4.0.0"
  }
}

 


 

이전과 동일하게 잘 되는 것을 확인할 수 있다.