본문 바로가기
IT/Javascript

Babel+Webpack 설정방법

by DOSGamer 2022. 8. 30.
반응형

Babel ?

자바스크립트 컴파일러로 최신 자바스크립트를 표준 자바스크립트로 변환해준다 (Transpiler) ES6 문법을 CommonJS 로 변환해서 모든환경에서 실행될 수 있게 해준다 ES6 모듈은 Chrome 61, FireFox 60, Safari 10.1, Edge 16 이상에서 사용할 수 있다

NodeJS 는 CommonJS 밖에 인식을 못하기 때문에 Babel 을 사용해야 소스를 ES6 문법으로 사용할 수 있다

babel 의 처리 방식은 polyfilltransform-runtime 방식이 있음

  1. polyfill : 구현체 전체 js 파일을 사용 - 사용하지 않는 기능도 변환
  1. transform-runtime : 실제 작업자가 사용한 기능에 대해서만 변환

babel-polyfill 과 babel-plugin-transform-runtime 세부 비교

https://programmingsummaries.tistory.com/401
https://programmingsummaries.tistory.com/401

  • @babel/cli : terminal 에서 babel 을 실행 시키는 기능
  • @babel/core : babel 의 기본적인 기능
  • @babel/preset-env : babel 이 컴파일 시킬 자바스크립트 스펙을 다 사용가능한 기능
  • @babel/node : babel 을 nodeJS 에서 사용하기 위한 기능
  • @babel/polyfill : 새로 추가된 객체들 (Promise, Map, Set)을 사용가능한 객체로 바꿔주는 기능

설치

# babel 기본 라이브러리
npm install --save-dev @babel/core @babel/cli

# babel preset
npm install --save-dev @babel/preset-env

# babel
npm install --save-dev @babel/node
# ployfill 은 실제환경에서 사용되어야 하기에 dev 로 설치하지 않는다 
npm install --save @babel/polyfill

babel 의 공식 preset

@babel/preset-env

@babel/preset-flow

@babel/preset-react

@babel/preset-typescript

설정

/* babel.config.js */
module.exports = {
  presets: [
    '@babel/preset-env'
  ],
/* plugin 설정 */
	plugins: [
		'@babel/plugin-proposal-class-properties'
	]
}

트랜스파일링

package.json 에서 scripts 로 추가한다

src/js 폴더를 -w (watch) 감지하여 자동으로 변환하고 dist/js 폴더로 -d (out-dir) 결과물을 저장한다

/* package.json */
"scripts": {
	"build": "babel src/js -w -d dist/js"
}

실행

npm run build

Babel Polyfill

# ployfill 은 실제환경에서 사용되어야 하기에 dev 로 설치하지 않는다 
npm install --save @babel/polyfill

파일에서 Polyfill 사용

/* main.js */
import "@babel/polyfill";

webpack 에서 Polyfill 사용

/* webpack.config.js
	entry 에 배열로 추가해준다
 */
module.exports = {
  // entry files
  entry: ['@babel/polyfill', './src/js/main.js'],

참조사이트

Usage Guide · Babel
There are quite a few tools in the Babel toolchain that try to make it easy for you to use Babel whether you're an "end-user" or building an integration of Babel itself. This will be a quick introduction to those tools and you can read more about them in the "Usage" section of the docs.
https://babeljs.io/docs/en/usage

Webpack ?

의존 관계에 있는 모듈들을 하나의 자바스크립트 파일로 번들링하는 모듈 번들러이다 장점 : 하나의 파일로 번들링 되어 별도의 모듈 로더가 필요없고, 다수의 자바스크립트 파일을 하나의 파일로 번들링하여 html 에서 여러개의 script 태그를 쓰지 않아도 된다
  • webpack : webpack 의 기본적인 기능
  • webpack-cli : terminal 에서 webpack 을 실행시키는 기능
  • babel-loader : webpack 이 모듈번들링시에 babel 을 사용하도록 하는 plug-in

설치

# 기본 라이브러리
npm install --save-dev webpack webpack-cli

# babel 연동 plugin
npm install --save-dev babel-loader

설정

babel 에는 babel.config.js 가 있다면 webpack 에는 webpack.config.js 가 있다

/* webpack.config.js */
const path = require('path');

module.exports = {
  // enntry file
  entry: './src/js/main.js',
  // 컴파일 + 번들링된 js 파일이 저장될 경로와 이름 지정
  output: {
    path: path.resolve(__dirname, 'dist/js'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        include: [
          path.resolve(__dirname, 'src/js')
        ],
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env'],
            plugins: ['@babel/plugin-proposal-class-properties']
          }
        }
      }
    ]
  },
  devtool: 'source-map',
  // https://webpack.js.org/concepts/mode/#mode-development
  mode: 'development'
};

실행

/* package.json */
"scripts": {
    "build": "webpack -w"
},
npm run build

운영환경용 설정

# 운영환경 배포용 plugin
npm install --save-dev html-webpack-plugin webpack-dev-server clean-webpack-plugin

설정

/* webpack.config.js */
const path = require("path");
const webpack = require("webpack");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = (env,options) => {
	const config = {
		entry: {
			app: ["@babel/polyfill", "./src/js/main.js"]
		},
		output: {
			filename: "[name].bundle.js",
			path: path.resolve(__dirname, "dist/js")
		},
	  module: {
	    rules: [
	      {
	        test: /\.js$/,
	        include: [
	          path.resolve(__dirname, 'src/js')
	        ],
	        exclude: /node_modules/,
	        use: {
	          loader: 'babel-loader',
	          options: {
	            presets: ['@babel/preset-env'],
	            plugins: ['@babel/plugin-proposal-class-properties']
	          }
	        }
	      }
	    ]
	  },
		optimization: {
			splitChunks: {
				cacheGroups: {
					commons: {
						test: /[\\/]node_modules[\\/]/,
						name: "vendors",
						chunks: "all"
					}
				}
			}
		}
	};

	if (options.mode === "development") {
		config.plugins = [
			new webpack.HotModuleReplacementPlugin(),
			new HtmlWebpackPlugin({
				template: path.join(__dirname, "/public/index.html"),
				showErrors: true
			})
		];
		config.devtool = "inline-source-map";
		config.devServer = {
			hot: true,
			contentBase: "./dist/js"
		};
	} else {
		config.plugins = [
			new CleanWebpackPlugin(),
			new HtmlWebpackPlugin({
				template: path.join(__dirname, "/public/index.html"),
				showErrors: true
			})
		];
	}
	return config;
};

테스트

/* package.json */
"scripts": {
	"dev": "webpack-dev-server --open --mode development",
	"build": "webpack --mode production",
	"babel": "babel src/js --out-dir dist/js" 
}

Sass

webpack 을 통해 Sass 를 컴파일 하는 방법

webpack plug-in ( Sass ⇒ CSS )

  • node-sass
  • style-loader
  • css-loader
  • sass-loader

설치

npm install --save-dev node-sass style-loader css-loader sass-loader

설정

const path = require('path');

module.exports = {
  // entry files
  entry: ['@babel/polyfill', './src/js/main.js', './src/sass/main.scss'],
  // 컴파일 + 번들링된 js 파일이 저장될 경로와 이름 지정
  output: {
    path: path.resolve(__dirname, 'dist/js'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        include: [
          path.resolve(__dirname, 'src/js')
        ],
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env'],
            plugins: ['@babel/plugin-proposal-class-properties']
          }
        }
      },
      {
        test: /\.scss$/,
        use: [
          "style-loader", // creates style nodes from JS strings
          "css-loader",   // translates CSS into CommonJS
          "sass-loader"   // compiles Sass to CSS, using Node Sass by default
        ],
        exclude: /node_modules/
      }
    ]
  },
  devtool: 'source-map',
  // https://webpack.js.org/concepts/mode/#mode-development
  mode: 'development'
};

실행

npm run build

결과물

bundle.js 안에 css 가 포함되어 있다undle.js 안에 css 가 포함되어 있다

bundle.js 에서 css 분리방법

설치

npm install --save-dev mini-css-extract-plugin

설정

/* webpack.config.js */
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
  // entry files
  entry: ['@babel/polyfill', './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-proposal-class-properties']
          }
        },
        exclude: /node_modules/
      },
      {
        test: /\.scss$/,
        use: [
          MiniCssExtractPlugin.loader,
          'css-loader',
          'sass-loader'
        ],
        exclude: /node_modules/
      }
    ]
  },
  devtool: 'source-map',
  // https://webpack.js.org/concepts/mode/#mode-development
  mode: 'development'
};

운영환경 설정 추가하기


Uploaded by N2T

반응형

'IT > Javascript' 카테고리의 다른 글

JavaScript Key code  (0) 2023.03.17
Javascript 함수형 예제  (0) 2022.08.30
Javascript 객체 복사 (Object, Array)  (0) 2022.08.10
두 정수 사이의 합  (0) 2022.07.14
약수의 합  (0) 2022.07.14
행렬의 덧셈  (0) 2022.07.14
수박수박수박수박수박수?  (0) 2022.07.14
문자열을 정수로 바꾸기  (0) 2022.07.14