Webpack - 시작하기
이번 포스팅에서 webpack 공식사이트의 getting started로 기본 개념을 익혀보도록 합니다.
Webpack?Permalink
- 자바스크립트 코드가 많아지고 거대화되면서 파일을 관리하는 것이 힘들어졌습니다. Webpack은 이러한 점들을 쉽게 지원하는 도구 중 하나입니다.
- 코드의 유지보수를 쉽게하고, 모듈화, 번들 등 프론트 엔드 개발을 위한 다양한 기능을 가지고 있습니다.
InstallationPermalink
npm init -y #node config initialize
npm install webpack --save-dev
npm install webpack-cli --save-dev
- webpack을 설치하기 위해서는 npm이 필요하기 때문에 먼저 node와 npm을 설치해야합니다.
- 그 후에, webpack과 webpack-cli를 설치합니다. webpack-cli는 webpack을 사용할 때 유용한 도구이며, webpack4이상을 사용할려면 cli설치는 필수입니다.
BundlePermalink
function component() {
const element = document.createElement('div');
// Lodash, currently included via a script, is required for this line to work
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
return element;
}
document.body.appendChild(component());
<!doctype html>
<html>
<head>
<title>Getting Started</title>
<script src="https://unpkg.com/lodash@4.16.6"></script>
</head>
<body>
<script src="../src/index.js"></script>
</body>
</html>
|- /node_modules
|- package.json
|- /dist
|-index.html
|- /src
|- index.js
- 예제는 공식 홈페이지의 예제를 들고 왔습니다.
- webpack을 설치하고 보통의 프로젝트 구조를 잡으면 위와 같은 디렉토리 구조가 됩니다.
- src는 소스코드가 작성되는 디렉토리이고, dist는 배포되는 컨텐츠가 저장됩니다. 여기에는 나중에 src가 묶여지는 bundle도 포함됩니다.
- index.html에 script로 추가된 내용을 번들로 만들기 위해서 lodash를 import합니다. 그리고 그에 맞게 index.html을 조정합니다. 번들로 만들어질 파일은 main.js입니다.
- lodash를 임포트 하기 위해서는 미리 npm으로 설치할 필요가 있습니다.
npm install lodash --save
//src/index.js
+ import _ form 'lodash';
...
<!-- dist/index.html -->
<!doctype html>
<html>
<head>
<title>Getting Started</title>
- <script src="https://unpkg.com/lodash@4.16.6"></script>
</head>
<body>
- <script src="./src/index.js"></script>
+ <script src="main.js"></script>
</body>
</html>
- Node 8.2/npm 5.2.0 이상은 npx webpack으로 번들을 할 수 있습니다.
- 이때 npx는 ./node_modules/.bin/webpack을 실행합니다.
ConfigPermalink
- Webpack 설정파일은 webpack.config.js 파일입니다.
- 이 파일을 프로젝트 루트경로에 놓고 실행하면 설정파일의 내용이 적용됩니다.
// 설정 파일 예시
const path = require('path');
module.exports = {
entry: './src/index.js', // 번들의 시작 js파일
output: {
filename: 'main.js', // 번들 결과물 이름
path: path.resolve(__dirname, 'dist')
}
};
참고