Webpack Part 1. core concepts

Eye0n·2020년 12월 1일
0

webpack

목록 보기
1/6
post-thumbnail

이글은 여러 포스트로 완성될 것이며 공식 홈페이지를 번역해서 나름대로 이해하기 위해 쓴 글입니다.

Webpack

webpack이란 정적 모듈 번들러이다.

자바스크립트에서 모듈이란 js로 이루어진 작은 기능단위 코드를 지칭한다.

하지만, webpack은 js의 모듈뿐만 아니라 스타일시트,이미지 등 모든 것을 자바스크립트 모듈로 로딩해서 사용한다.

1. Core Concepts

Entry, Output, Loaders, Plugins, Mode, Browser Compatibility

먼저 webpack의 핵심과정은 entry -> loaders -> plugins -> output 이렇게 된다.

Entry

공식문서에 따르면 webpack이 내부 의존성 그래프가 빌드되는 시작점으로 사용되는 모듈을 가리킨다.

즉, webpack으로 모듈화되기 위한 인풋값이다.
여기서 내부 의존성 그래프가 의미하는 것은 인풋되는 파일이 가진 import되어 쓰이는 다른 패키지들에 대한 의존성을 의미한다.

webpack.config.js

const path = require('path');

module.exports = {
  entry: {
    main: './path/to/my/entry/file.js',
    path: path.resolve(__dirname, 'dist')
  }
};

Output

webpack이 생성한 번들파일을 내보낼 위치와 해당 파일의 이름을 지정한다

webpack.config.js

module.exports = {
	...
  output: {
    path: path.resolve(__dirname, "/dist"),
    filename: '[name].bundle.js'    
  }
};

Loaders

webpack은 js와json파일만을 이해한다.
loader는 webpack이 다른 타입의 파일들을 처리하고 모듈로 변환시킬 수 있게 도와준다.

webpack.config.js

// 다른 타입 파일들에 대한 경우
module.exports = {
	...
  module: {
    rules: [
      { test: /\.css$/, use: 'css-loader' },
      { test: /\.ts$/, use: 'ts-loader' }
    ]
  }
};
// 같은 타입 파일에 대한 경우
module.exports = {
	...
  module: {
    rules: [
      { // 여러개인 경우 use: [ loaders... ]
        test: /\.css$/,
        use: [
          // [style-loader](/loaders/style-loader)
          { loader: 'style-loader' },
          // [css-loader](/loaders/css-loader)
          {
            loader: 'css-loader',
            options: {
              modules: true
            }
          },
          // [sass-loader](/loaders/sass-loader)
          { loader: 'sass-loader' }
        ]
      },
      { // 1개인 경우
        test: /\.(js|jsx)$/,
        use: 'babel-loader'
      }
    ]
  }
};

Plugins

loader가 모듈 변환 작업을 하는동안 plugin을 활용하여 번들 최적화, asset manangement, 환경변수 주입과 같은 광범위한 작업을 수행한다.

webpack.config.js

//installed via npm
const HtmlWebpackPlugin = require('html-webpack-plugin'); 

//to access built-in plugins
const webpack = require('webpack'); 
const path = require('path');

module.exports = {
  ...
  plugins: [
    new webpack.ProgressPlugin(),
    new HtmlWebpackPlugin({template: './src/index.html'})
  ]
};

Mode

Mode는 development, production or none 값을 가질 수 있으며 각 환경에 해당되는 webpack's built-in optimizations을 활성화 할 수 있다. default: production

webpack.config.js

module.exports = {
mode: 'production' || 'development' || none
};

Browser Compatibility

모든 브라우저를 지원한다 그러나 IE8과 이 이하 버전은 지원하지 않는다. 만약 이하 버전이 필요하다면 "load a polyfill"을 써야한다.


Reference

https://webpack.js.org/

0개의 댓글