웹팩 배우기 1
참고자료 Understanding the Modern Web Stack: Webpack - The Basics (link)
What is webpack?
- a bundler for javascript applications
Get started
install node; do it yourself
start a npm project
npm init -y
create two files
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="node_modules/lodash/lodash.min.js"></script> <script src="script.js" defer></script> </head> <body></body> </html>
script.js
with respect to whereindex.html
isfunction component () { const element = document.createElement('div'); element.innerHTML = _.join(['Hello', 'webpack'], ' '); return element; } document.body.appendChild(component());
install
lodash
npm install lodash
index.html
을 브라우저로 열면 Hello webpack 이 보인다. 이제 webpack을 이용해서 html을 로딩해보자. 먼저src
폴더를 만들고index.html
와script.js
를 옮긴다.install webpack
npm install webpack webpack-cli --save-dev
create webpack config file
webpack.config.js
const path = require("path"); module.exports = { mode: "none", entry: "./src/script.js", output: { filename: "main.js", path: path.resolve(__dirname, "dist") } }
그리고 webpack 를 실행하면
npx webpack
webpack.config.js
의entry
와output
에 적은 대로script.js
을 entry 포인트로 시작해서webpack
이 번들링을 하여main.js
을 생성시킨다.. ├── dist │ └── main.js
하지만 index.html 여전히 script.js 를 가르키고 있는 상황 따라서
HtmlWebpackPlugin
을 사용하여 해결한다.npm install html-webpack-plugin --save-dev
update
webpack.config.js
const path = require("path"); const HtmlWebpackPlugin = require("html-webpack-plugin") ; module.exports = { mode: "none", entry: "./src/script.js", output: { filename: "main.js", path: path.resolve(__dirname, "dist") }, plugins: [ new HtmlWebpackPlugin({ filename: "index.html", template: "./src/index.html", }), ], }
after this, we need to remove two lines of
<script>
tag from html and runnpx webpack
. and there you go we haveindex.html
indist
folder and<scrip>
tag formain.js
is added therein bywebpack
. ├── dist │ ├── index.html │ └── main.js
하지만
index.html
을 로딩해보면 에러가 나는데lodash
때문이다.script.js
에 다음을 추가해주면 해결된다.
// script.js
import _ from 'lodash';
- 하지만 또다른 문제는
lodash
팩키지 전체를 import 해왔기 때문에 번들 파일main.js
의 크기가 필요이상을 크다는 것. - 해결 방법은
script.js
에서 사용하는 모듈만 import 해오는것// before import _ from 'lodash';
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
// after
import join from 'lodash/join';
element.innerHTML = join(['Hello', 'webpack'], ' ');