웹팩 치트시트
39639 단어 webdevjavascriptwebpackproductivity
목차
Webpack Cheatsheet
[to import stuff]
[to perform actions]
[adding bootstrap,font awesome]
웹팩 치트시트
Link to an Awesome Webpack Boilerplate : Athlon Webpack boilerplate
내 모든 시트 모음은 Github에 있습니다.
설치
npm install webpack webpack-cli --save-dev
//webpack.config.js
const path = require("path");
module.exports = {
entry: "./src/index.js",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "./dist"),
},
mode: "none",
};
Webpack을 사용하여 이제 데이터와 파일을 서로 간에 내보내고 가져올 수 있습니다.
로더
webpack을 사용하여 항목을 가져오는 데 도움이 되는 라이브러리
이미지 추가
npm install file-loader --save-dev
//webpack.config.js
module.exports = {
entry: "./src/index.js",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "./dist"),
publicPath: "", /* to specify image location for html , website URL in production */
},
mode: "none",
module: {
rules: [
{
test: /\.(png|jpg)$/,
use: ["file-loader"],
},
],
},
};
//index.js
import Kiwi from "./kiwi.jpg";
JS에 CSS 추가
npm install style-loader css-loader --save-dev
//webpack.config.js
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
//component.js
import "./hello-world-button.css";
SCSS 추가
npm install sass-loader sass --save-dev
//webpack.config.js
{
test: /\.scss$/,
use: ["style-loader", "css-loader", "sass-loader"], //first style-loader at last sass-loader
},
//component.js
import "./hello-world-button.scss";
바벨 추가
npm install @babel/core babel-loader @babel/preset-env babel-plugin-transform-class-properties --save-dev
//webpack.config.js
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["@babel/env"],
plugins: ["transform-class-properties"],
},
},
},
플러그인
플러그인은 가져온 항목에 대해 특정 작업을 수행합니다.
JS 축소
npm install terser-webpack-plugin --save-dev
//webpack.config.js
const TerserPlugin = require("terser-webpack-plugin");
/* Inside Module.exports */
plugins: [new TerserPlugin()],
CSS를 특정 파일로 추출
npm install mini-css-extract-plugin --save-dev
//webpack.config.js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
rules = [
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader"],
},
{
test: /\.scss$/,
use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"],
},
]
}
plugins: [
new MiniCssExtractPlugin({
filename: "style.css",
}),
],
실행마다 새 파일 이름 생성(내용 변경 시에만)
//simple add [contenthash] to the filename you want to have new name
filename: "bundle.[contenthash].js",
모든 빌드에서 이전 파일 삭제 및 새 렌더링
npm install clean-webpack-plugin --save-dev
//webpack.config.js
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
// Running This PLugin without option , will automatically clean dist folder
plugins: [
new CleanWebpackPlugin({
cleanOnceBeforeBuildPatterns: [
"**/*", //this runs by default in dist folder
path.join(process.cwd(), "build/**/*"), //adding other folders
],
}),
],
Webpack을 사용하여 HTML 생성
npm install html-webpack-plugin --save-dev
//webpack.config.js
const HtmlWebpackPlugin = require("html-webpack-plugin");
plugins: [
new HtmlWebpackPlugin(), //generates default html file
]
//publicPath can be empty as html is generated in the same place as other files by default. (the path specified)
- 수동 HTML 옵션 지정
new HtmlWebpackPlugin({ //extra options for the html file
title: "Hello World",
filename: "subfolder/custom_filename.html",
meta: {
description: "Some Description",
},
}),
- HTML 템플릿 엔진(HandleBars) 사용
npm install handlebars-loader --save-dev
npm install handlebars --save
// Add a Test in module rules for hbs files to use handlebars loader
{
test: /\.hbs$/,
use: ["handlebars-loader"],
}
//Also add the new plugin to access hbs
new HtmlWebpackPlugin({
title: "Hello World",
template: "src/index.hbs",
description: "Some Description",
}),
개발 및 생산 빌드
모드 변경
//webpack.config.js
module.exports = {
mode : "production", //for production (here no source or anything is done)
mode : "development", //source maps are rendered and development is faster
mode : "none" //to not use any mode
}
다른 모드에 대해 다른 구성 만들기
Link to an Awesome Webpack Boilerplate : Athlon Webpack boilerplate
npm install webpack webpack-cli --save-dev
//webpack.config.js
const path = require("path");
module.exports = {
entry: "./src/index.js",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "./dist"),
},
mode: "none",
};
npm install file-loader --save-dev
//webpack.config.js
module.exports = {
entry: "./src/index.js",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "./dist"),
publicPath: "", /* to specify image location for html , website URL in production */
},
mode: "none",
module: {
rules: [
{
test: /\.(png|jpg)$/,
use: ["file-loader"],
},
],
},
};
//index.js
import Kiwi from "./kiwi.jpg";
npm install style-loader css-loader --save-dev
//webpack.config.js
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
//component.js
import "./hello-world-button.css";
npm install sass-loader sass --save-dev
//webpack.config.js
{
test: /\.scss$/,
use: ["style-loader", "css-loader", "sass-loader"], //first style-loader at last sass-loader
},
//component.js
import "./hello-world-button.scss";
npm install @babel/core babel-loader @babel/preset-env babel-plugin-transform-class-properties --save-dev
//webpack.config.js
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["@babel/env"],
plugins: ["transform-class-properties"],
},
},
},
npm install terser-webpack-plugin --save-dev
//webpack.config.js
const TerserPlugin = require("terser-webpack-plugin");
/* Inside Module.exports */
plugins: [new TerserPlugin()],
npm install mini-css-extract-plugin --save-dev
//webpack.config.js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
rules = [
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader"],
},
{
test: /\.scss$/,
use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"],
},
]
}
plugins: [
new MiniCssExtractPlugin({
filename: "style.css",
}),
],
//simple add [contenthash] to the filename you want to have new name
filename: "bundle.[contenthash].js",
npm install clean-webpack-plugin --save-dev
//webpack.config.js
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
// Running This PLugin without option , will automatically clean dist folder
plugins: [
new CleanWebpackPlugin({
cleanOnceBeforeBuildPatterns: [
"**/*", //this runs by default in dist folder
path.join(process.cwd(), "build/**/*"), //adding other folders
],
}),
],
npm install html-webpack-plugin --save-dev
//webpack.config.js
const HtmlWebpackPlugin = require("html-webpack-plugin");
plugins: [
new HtmlWebpackPlugin(), //generates default html file
]
//publicPath can be empty as html is generated in the same place as other files by default. (the path specified)
new HtmlWebpackPlugin({ //extra options for the html file
title: "Hello World",
filename: "subfolder/custom_filename.html",
meta: {
description: "Some Description",
},
}),
npm install handlebars-loader --save-dev
npm install handlebars --save
// Add a Test in module rules for hbs files to use handlebars loader
{
test: /\.hbs$/,
use: ["handlebars-loader"],
}
//Also add the new plugin to access hbs
new HtmlWebpackPlugin({
title: "Hello World",
template: "src/index.hbs",
description: "Some Description",
}),
//webpack.config.js
module.exports = {
mode : "production", //for production (here no source or anything is done)
mode : "development", //source maps are rendered and development is faster
mode : "none" //to not use any mode
}
//package.json
"scripts": {
"build": "webpack --config webpack.production.config.js",
"dev": "webpack --config webpack.dev.config.js"
},
개발 모드에서 Webpack-dev-server 사용
npm install webpack-dev-server --save-dev
//webpack.dev.config.js
module.exports = {
devServer: {
contentBase : path.resolve(__dirname, "./dist"),
index: 'index.html',
port: 9000
}
}
//package.json
scripts = {
"dev": "webpack-dev-server --config webpack.dev.config.js --hot"
}
다중 페이지 애플리케이션
여러 페이지 렌더링
//webpack.production.config.js
module.exports = {
entry: {
'hello-world': './src/hello-world.js', //file 1
'kiwi': './src/kiwi.js', // file 2
},
output: {
filename: "[name].[contenthash].js", //will generate different names
path: path.resolve(__dirname, "./dist"),
publicPath: "",
},
plugins: [
new MiniCssExtractPlugin({
filename: "[name].[contenthash].css", //same for css files
}),
new HtmlWebpackPlugin({
filename: 'hello-world.html', //different Html Files
chunks: ['hello-world'], //is used from entry point
title: "Hello World",
description: "Hello World",
template: "src/page-template.hbs",
}),
new HtmlWebpackPlugin({
filename: 'kiwi.html',
chunks: ['kiwi'], //specify only the ones u need
title: "Kiwi",
description: "Kiwi",
template: "src/page-template.hbs",
}),
]
}
종속성에 대한 공통 파일 생성
//webpack.production.config.js
module.exports = {
optimization: {
splitChunks: {
chunks: "all", //this will integrate all the extra packages into one extra js file
minSize : 10000, //this specifies the minimum size of the bundle to split
automaticNameDelimiter: '_' //this specifies the separation between file names , by default ~
}
},
plugins : [
new HtmlWebpackPlugin({
chunks: ['hello-world'],
}),
new HtmlWebpackPlugin({
chunks: ['kiwi'],
}),
] // integrating the extra modules js file into the HTML
}
엑스트라
사용자 지정 글꼴 추가
//webpack.config.js
{
test: /\.{woff2|woff}$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/',
}
}
],
}
//add font face in scss
//import scss in js
부트스트랩 추가
npm install bootstrap jquery popper.js --save
import "bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";
npm install postcss-loader precss autoprefixer --save-dev
//webpack.config.js
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
{
loader: "postcss-loader",
options: {
plugins: function () {
return [require("precss"), require("autoprefixer")];
},
},
},
"sass-loader",
],
//index.scss
@import "~bootstrap/scss/bootstrap";
멋진 글꼴 추가
npm install --save-dev @fortawesome/fontawesome-svg-core @fortawesome/free-solid-svg-icons @fortawesome/free-regular-svg-icons @fortawesome/free-brands-svg-icons
//index.js
import { library, dom } from "@fortawesome/fontawesome-svg-core";
//library is used to import the specific icon , dom replaces i tag in DOM
import { faSpinner } from "@fortawesome/free-solid-svg-icons";
// import only the icons needed
library.add(faSpinner); //puts the icon in the library
dom.watch(); //watches for changes in the html, and replaces every font awesome <i> tag
<!-- index.html -->
<i class="fas fa-spinner fa-spin"></i>
<!-- simply consume the icon needed -->
ESLint
npm install eslint babel-eslint --save-dev
.eslintrc.json
(생성 가능, 문서 확인){
"extends": "eslint:recommended", //recommended settings
"parser": "babel-eslint", // babel for classes
"parserOptions": { //for es6 import and others
"ecmaVersion": 6,
"sourceType": "module"
},
"env": {
"node": true, //tells we are using node , for "require"
"browser": true //tells running in browser , for "document"
},
"rules": { //specific rules that we want to add
"no-console": 0
}
}
eslint .
를 사용하여 eslint를 수동으로 실행Reference
이 문제에 관하여(웹팩 치트시트), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/zinox9/webpack-cheatsheet-7pj텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)