TIL.22.07.25
webpack
여러 개의 파일을 하나의 파일로 합쳐주는 모듈 번들러를 의미합니다. 모듈 번들러란 HTML, CSS, JavaScript 등의 자원을 전부 각각의 모듈로 보고 이를 조합해 하나의 묶음으로 번들링(빌드)하는 도구입니다.
entry
webpack이 내부의 디펜던시 그래프를 생성하기 위해 사용해야 하는 모듈입니다. Webpack은 이 Entry point를 기반으로 직간접적으로 의존하는 다른 모듈과 라이브러리를 찾아낼 수 있습니다.
//기본 값
module.exports = {
...
entry: "./src/index.js",
};
//지정 값
module.exports = {
...
entry: "./src/script.js",
};
output
생성된 번들을 내보낼 위치와 이 파일의 이름을 지정하는 방법을 webpack에 알려주는 역할을 합니다.
const path = require('path');
module.exports = {
...
output: {
path: path.resolve(__dirname, "docs"), // 절대 경로로 설정을 해야 합니다.
filename: "app.bundle.js",
clean: true
},
};
loader
Webpack이 다른 유형의 파일을 처리하거나, 그들을 유효한 모듈로 변환해 애플리케이션에 사용하거나 디펜던시 그래프에 추가할 수 있습니다.
- test: 변환이 필요한 파일들을 식별하기 위한 속성
- use: 변환을 수행하는데 사용되는 로더를 가리키는 속성
- exclude: 바벨로 컴파일하지 않을 파일이나 폴더를 지정. (반대로 include 속성을 이용해 반드시 컴파일해야 할 파일이나 폴더 지정 가능)
test와 use속성은 필수 속성입니다. 이런 속성을 넣어 규칙을 정하기 위해서는 module.rules 아래에 정의해야 합니다. 그저 rules아래에 정의하면 webpack은 경고를 하게 됩니다.
module.exports = {
...
module: {
rules: [
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader"],
exclude: /node_modules/,
},
],
},
};
plugin
번들을 최적화하거나 에셋을 관리하고, 또는 환경변수 주입 등의 광범위한 작업을 수행할 수 있게 됩니다.
const webpack = require('webpack');
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
...
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, "src", "index.html"),
}),
new MiniCssExtractPlugin(),
],
};
-명령어-
npm init -y
package.json 파일 생성.
npm install -D webpack webpack-cli
webpack 과 webpack-cli 설치
-D 는 현재 파일에서만 사용하겠다는 뜻.
webpack.config.js 파일 생성 => 일단 js 파일과는 이미지가 다름.
// webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'), // './dist'의 절대 경로를 리턴합니다.
filename: 'app.bundle.js',
},
};
entry : 시작지점.
output : 파일을 생성하는 지점.
=> src.index.js 파일을 dist/app.bundle.js 파일로 번들링 한다.
npx webpack
번들링 하기
package.json 파일의 script 명령어 추가하기
"build": "webpack",
원래는 test 만 있다. 하지만 위 코드를 추가해줘야 npm run build 를 했을 때 명령어가 실행됨.
require('./style.css');
CSS를 부르기 위해서는 js 파일에서 위코드를 작성해줄것.
--> 여기까지 작성 후 node src.index.js 파일을 실행하면 loader 필요하다는 오류를 볼 수 있다. <--
npm i -D css-loader style-loader
css 관련 loader 설치 명령어
앞에서 작성했던 webpack.config.js 파일을 수정한다.
// webpack.config.js
const path = require("path");
module.exports = {
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "app.bundle.js",
},
module: {
rules: [
{
// 파일명이 .css로 끝나는 모든 파일에 적용
test: /\.css$/,
// 배열 마지막 요소부터 오른쪽에서 왼쪽 순으로 적용
// 먼저 css-loader가 적용되고, styled-loader가 적용되어야 한다.
// 순서 주의!
use: ["style-loader", "css-loader"],
// loader가 node_modules 안의 있는 내용도 처리하기 때문에
// node_modules는 제외해야 합니다
exclude: /node_modules/,
},
],
},
};
loader 는 css 가 먼저 실행되고 style이 나중에 실행되어야 한다.
==> 배열 뒤쪽부터 실행된다 === 순서주의해라.
npm i -D html-webpack-plugin
webpack plug in 설치 명령어
webpack.config.js파일에 코드추가.
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: "./src/index.js",
output: {
... 생략...
plugins: [new HtmlWebpackPlugin({
template: path.resolve(__dirname, "src", "index.html")
})]
};
dist 파일 안에 index.html 파일이 생성된다.