webpack + babel

김태완·2021년 11월 12일
0

프론트엔드

목록 보기
9/30

웹팩이란?

  • 모듈단위의 js들을 모아서 하나의 app.js로 번들링해주는 기능

바벨이란?

  • 크로스브라우징을 위해 es6문법으로 작성된 js를 es5로 변환해주는 기능

웹팩 + 바벨 설정과정

  1. 루트폴더에 npm init을 해준다.
    *이때 폴더에 package.json파일이 생겨남

  2. 웹팩과 바벨을 설치해준다
    *웹팩 바벨은 개발모드에서만 사용

npm i -D webpack
npm i -D webpack-cli
npm i -D @babel/core
npm i -D @babel/preset-env
npm i -D @babel/preset-react
npm i -D babel-loader
  1. 최상위 위치에 webpack.config.js 파일을 생성
    *기본적인 구조는 아래와 같다, 최상단에는 모드설정에 관한내용, entry는 번들링 할 js들을 명시, module은 웹팩과정에서의 옵션, output은 최종 결과물의 위치에 대한설정이다
const {webpack} = require('webpack');

module.exports ={
	name : '',
   	mode : '',
    	devtool : '',
    
    	entry : {

    	},
    
    	module : {

    	},
    
    	output : {

    	}

}

  1. 웹팩 핫로더
    웹팩 사용시 매번 npm run [명령어]를 해줘야지 변경사항을 볼 수 있다.
    개발환경에서 실시간으로 변경사항을 보기위해 hot loader를 사용한다
npm i -D @pmmmwh/react-refresh-webpack-plugin
npm webpack-dev-server

최종 webpack.config.js 내용

const path = require('path');
const webpackRefresh = require('@pmmmwh/react-refresh-webpack-plugin');
const { webpack } = require('webpack');

module.exports = {
    name : 'reactStudy',
    mode : 'development',
    devtool : 'eval',
    resolve : {
        extensions : ['.js', '.jsx']
    },
    // 입력
    entry : {
        app : ['./client.jsx'],
    },
    // 룰 -> loaders라고함
    module: {
        rules: [{
            test : /\.jsx?/,
            loader :  'babel-loader',
            options : {
                presets : [
                    ['@babel/preset-env', {
                        targets : {
                            browsers : ['> 0.1% in KR', 'last 2 chrome versions'],  //browserlist 사이트 참고
                        },
                        debug : true,
                    }], 
                    '@babel/preset-react',
                ],
                plugins : [
                    '@babel/plugin-proposal-class-properties',
                    'react-refresh/babel',
                ],
                
            }
        }]
    },
    // 웹팩기능 외의 추가작업
    plugins : [
        new webpackRefresh() // 핫로더 사용
    ],
    //출력
    output : {
        path : path.join(__dirname, 'dist'),
        filename : 'app.js',
        publicPath : '/dist',
    },
    devServer: {  //핫로더 서버
        devMiddleware : { publicPath : '/dist'},
        static : { directory : path.resolve(__dirname)},
        hot: true,
    },
}

브라우저 옵션 : https://github.com/browserslist/browserslist

profile
프론트엔드개발

0개의 댓글