웹팩 과제
간단한 웹앱 번들링
src에 js,html,css 파일을 넣는다.
1.현재 디렉토리에 npm 설치
npm init -y
설치후 package.json 파일이 생성된다.
2. webpack 설치
npm install -D webpack webpack-cli
Node.js 프로젝트에서 webpack과 webpack-cli를 개발 의존성(dependency)으로 설치하는 것을 의미
3. webpack.config.js 파일 만들기
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'app.bundle.js',
path: path.resolve(__dirname, 'dist'),
},
}
4.js 파일 번들링
npx webpack
"scripts": {
"build": "webpack",
"test": "echo \"Error: no test specified\" && exit 1"
},
npm run build로 번들링이 가능하다.
번들링 결과 output으로 지정해준 dist 폴더가 생겼다.
dist안에 app.bundle.js파일에 한줄코드로 바꿨다.
HTML파일 번들링
html-webpack-plugin 설치
npm i -D html-webpack-plugin
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
filename: 'app.bundle.js',
path: path.resolve(__dirname, 'dist'),
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'src', 'index.html'),
}),
],
};
npm run build 로 번들링
dist 폴더에 index.html 파일이 생성
CSS 번들링
style-loader 와 css-loader 설치
npm i -D style-loader css-loader
index.js
import './style.css";
로더 등록
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
filename: 'app.bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module : {
rules: [{
test: /\.css$/,
use: ["style-loader", "css-loader"],
exclude: /node_modules/,
}]
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'src', 'index.html'),
}),
],
};
npm run build 로 번들링
webpack.config.js 에서 output을 dist에서 docs로 바꾸기
이미 번들링된 dist파일이름을 docs로 바뀜
깃헙 페이지 배포가 목표라면 애초에 output을 docs로 설정하고 저장하기
빌드를 다 마치고 git push
현재 작업 중인 깃헙 리포지토리의 setting- pages에서 source 옵션을 main,
root를 /docs 폴더로 설정하고 저장한다.
npm i -D webpack-dev-server
변경된코드를 빠르게 개발 서버에 반영된다.
Advanced
- development mode와 production mode의 차이에 대해서 학습하고, config file을 나눠보세요
개발 모드에서는 빌드 결과물이 최적화되지 않고, 소스 맵이 포함되어 디버깅이 용이하도록 설정
빠르게 빌드하고 개발하는데 적합
반면에 프로덕션 모드에서는 빌드 결과물이 최적화되어 용량이 작아지고, 소스 맵이 제거되어 배포에 적합하도록 설정
module.exports = (env, argv) => {
const isDevelopment = argv.mode === 'development';
:
module :
devtool: isDevelopment ? 'eval-source-map' : false,
optimization: {
minimize: !isDevelopment,
},
}
- 번들링 할 때 마다 dist 디렉터리를 정리해보세요
output에서 clean:true
- app.bundle.js 가 아니라, output이 늘 동적으로 변하도록 생성해보세요.
output에서 filename: '[name].[contenthash].js', // 동적으로 변하는 파일 이름 설정
output 객체의 filename 속성에 [name].[contenthash].js 형식의 값을 지정해주면, app.bundle.js 대신 웹팩이 각각의 파일들마다 생성한 고유한 해시값으로 이름이 동적으로 지정
- CSS에 minify를 적용해봅니다.
plugin 설치
npm install mini-css-extract-plugin --save-dev
npm install css-minimizer-webpack-plugin --save-dev
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
module : {
rules: [{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader"],
exclude: /node_modules/,
}]
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'src', 'index.html'),
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css",
}),
],
optimization: {
minimize: true,
minimizer: [
new CssMinimizerPlugin(),
],
},
- ES6를 지원하지 않는 브라우저에서 실행 가능하게 target 속성을 활용
npm install --save-dev @babel/preset-env
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'app.bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
},
},
},
],
},
target: ['web', 'es5'],
};
target 속성은 ['web', 'es5']로 설정
이는 web 환경에서 ES5 버전을 지원하는 브라우저에서 실행 가능한 코드를 생성하도록 지정하는 것을 의미
React 번들링
CRA 반대
CRA란 ? d이미 개발자가 사용할 법한 설정은 다 들어있는 프로젝트
번들링 < 빌드
번들링 : 단순하게 여러개의 소스 코드들 -> 1개의 파일로 결합하는 과정
빌드 : 개발자가 작성한 코드들 웹서버에 실행 가능한 형태로 제공
웹팩 : javascript로만 된 모듈만 번들링하는 친구
바벨 로더 : 웹펙에서 사용하는 로더중 하나로 E56문법으로 작성된 코드를 ES5 문법으로 변환시켜주는 로더이다.
트랜스파일러 : 같은 언어지만 문법적으로 변환해주는 도구
트랜스파일러는 원본 소스 코드를 읽어들여 다른 언어의 소스 코드로 변환
개발자들이 언어를 변환할때 플러그인을 쓴다.
gitgnore 검색에서
맨첫번째 클릭
https://www.toptal.com/developers/gitignore
gitignore.io
Create useful .gitignore files for your project
www.toptal.com
react 와 node 검색하여 복붙
gitgnore 필요없는 폴더 제외