当前位置:网站首页>How to use webpach packer
How to use webpach packer
2022-05-14 14:00:07【Fish that want to be taken away】
Packager
effect :1. Pack the files together , Easy to develop , Reduce requests 2. Module loading
Official documents :https://webpack.docschina.org/
Webpach It can only be used for single page in the background
One :Webpach Concept
Concept :
Essentially ,webpack It's a modern JavaScript Application's Static module packager (module bundler). When webpack When processing an application , It builds one recursively Dependency graph (dependency graph), It contains each module required by the application , All these modules are then packaged into one or more bundle.
from webpack v4.0.0 Start , You don't need to introduce a configuration file , But use the naming rules it specifies
You can also configure files
entry and output At the core of , You have to configure entrance (entry) Output (output) loader plug-in unit (plugins)
Two : Basic steps
Create a new folder
webpack.config.js
fileconst path = require('path'); // Configure inlet and outlet module.exports = { entry: './src/main.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'my-first-webpack.bundle.js' } };
Build a src Folder ( Source code directory )
dist Folder , Store packaged files js, Write in this html Then import your packaged file
npm init The initialization file is node npm i webpack webpack-cli download webpack plug-in unit npm i webpack webpack-cli -w Monitor changes in source code
start-up webpack
npx webpack npx webpack -w Start of monitoring
3、 ... and : load css
Because direct import The default import is js file , To import css You need to pass load To help
download css Plug in for
npm install --save-dev style-loader css-loader
Then finish it css After importing
import '../css/main.css'; import css from '../css/main.css';
webpack.config.js The content of
module.exports = { entry: './src/index.js', // entrance output: { // Output filename: 'bundle.js', path: path.resolve(__dirname, 'dist'), }, module: { rules: [ { test: /\.css$/i, // load css use: ['style-loader', 'css-loader'], }, { test: /\.(png|svg|jpg|jpeg|gif)$/i, // load images type: 'asset/resource', }, { test: /\.(woff|woff2|eot|ttf|otf)$/i, // Load Fonts type: 'asset/resource', }, ], }, };
Four : Load data
Besides , Useful resources that can be loaded and data , Such as JSON file ,CSV、TSV and XML. Be similar to NodeJS,JSON Support is actually built-in , in other words
import Data from './data.json'
By default, it will run normally . To import CSV、TSV and XML, You can use csv-loader and xml-loader. Let's deal with loading these three types of files :
Download plug-ins
npm install --save-dev csv-loader xml-loader
Import
import Data from './data.xml'; import Notes from './data.csv';
To configure
rules: [ { test: /\.css$/i, use: ['style-loader', 'css-loader'], }, { test: /\.(png|svg|jpg|jpeg|gif)$/i, type: 'asset/resource', }, { test: /\.(woff|woff2|eot|ttf|otf)$/i, type: 'asset/resource', }, { test: /\.(csv|tsv)$/i, use: ['csv-loader'], }, { test: /\.xml$/i, use: ['xml-loader'], }, ],
5、 ... and : Set up HtmlWebpackPlugin
Download plug-ins
npm install --save-dev html-webpack-plugin
Import files
const HtmlWebpackPlugin = require('html-webpack-plugin');
The configuration file
module.exports = { entry: { index: './src/index.js', print: './src/print.js', }, // If you want to join div If you want to share a template (template:src Under the index.html file ) plugins: [ new HtmlWebpackPlugin({ title: ' Manage output ', template:"./src/index.html" }), ], output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist'), }, };
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- If you write this in the title, you will use the title in the plug-in . --> <title><%= htmlWebpackPlugin.options.title %></title> </head> <body> <div id="macnum" class="box"></div> </body> </html>
6、 ... and : Use source map
When webpack When packaging source code , It can be hard to trace error( error ) and warning( Warning ) The original location in the source code . for example , If three source files (
a.js
,b.js
andc.js
) Pack it into a bundle(bundle.js
) in , And one of the source files contains an error , Then the stack trace will point directly tobundle.js
. You may need to know exactly which source file the error came from , So this tip usually doesn't help much .
To make it easier to track error and warning,JavaScript Provides source maps function , You can map the compiled code back to the original source code . If a mistake comes from
b.js
,source map Will clearly tell you .
source map There are many The available options , Be sure to read them carefully , So that it can be configured as needed .
For this guide , We will use
inline-source-map
Options , This helps explain the intent of the example ( This configuration is for example only , Don't use in a production environment ):
such as : Because the code has been packaged , But if there's something wrong in it , The number of lines he reported wrong is always the first line , So you need to see exactly what is wrong , Just add source map
go in , But this is a convenient time for development , When it's time to upload , Must put source map
It's closed , Otherwise, it will be on the web page , Everyone can copy See your source code
module.exports = {
mode: 'development',
entry: {
index: './src/index.js',
print: './src/print.js',
},
devtool: 'inline-source-map', // This is the sentence
plugins: [
new HtmlWebpackPlugin({
title: 'Development',
}),
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
clean: true,
},
};
7、 ... and : Use node The server opens the browser 、
localhost:3000
npm i: download node All documents ,npm init: Initialize project
Built in hot deployment : Write code here and render automatically there .
All static resources are placed in dist Inside , But in src The address of the import file inside should be written dist Relative road strength .
Method 1:
Download plug-ins
npm install --save-dev webpack-dev-server
To configure
module.exports = { mode: 'development', entry: { index: './src/index.js', print: './src/print.js', }, devtool: 'inline-source-map', // New addition devServer: { // Set up folders static: './dist', // Default port number 8080, You can customize port:3000 }, plugins: [ new HtmlWebpackPlugin({ title: 'Development', }), ], output: { filename: '[name].bundle.js', path: path.resolve(__dirname, 'dist'), clean: true, }, // New addition optimization: { runtimeChunk: 'single', }, // The default environment is production , Now for the development environment mode:'development', };
stay pakage.json Your ranking in start The startup method assigned as below
open Write that is to start hot deployment , If you don't write, you don't open
"start": "webpack serve --open",
If you want to change the port ( Remember to restart every time you change or add a new thing )
devServer: { static: './dist', port:3000 },
8、 ... and : How to solve cross domain problems
Directly in webpack.config.js Add inside
devServer: {
static: './dist',
port:'3000',
// Cross domain configuration is this
proxy: {
'/api': {
target: 'http://localhost:3001',
pathRewrite: {
'^/api': '' },
},
},
},
边栏推荐
- 逻辑回归(Logistic Regression)
- 【源码解析】StyleNeRF 之Train_encoder.py
- moderlarts第一次学习
- 为什么调用了BrandMapper里面的addBrand方法,这个方法已经给我一个返回值了,也在方法里面提交事务了,但是数据库还是没有增加数据
- 2022年5月7日刷题
- 2022.5.7-----leetcode.433
- 2022年5月7号博客内容SSM框架项目管理-------------超市管理系统(第十一课针对订单管理修改表中的数据表的数据)
- C#,扫雷游戏(Minesweeper)之壹——作弊手段大曝光
- 【开源库学习】OpenThreads
- 【OSG】Examples
猜你喜欢
随机推荐
- postman循环调用同一个接口
- (Transfer Learning and fine tuning)迁移学习与微调
- ICDAR 2021竞赛 科学文献分析——表格识别综述部分(剩余部分是文档布局分析)
- Webpach打包器的如何使用
- 2021-IEEE论文-深度神经网络在文档图像表格识别中的应用现状及性能分析
- vscode搭建go开发环境
- chrome 安装axure 插件
- P4 learning - Basic forwarding
- The contents of the input box are displayed on the right
- Clickhouse 22.3 lts release
- Programmer flirting special ~ ~ ~ nice H5 cube creative photo album, resources free!!! A gift from a programmer to a girl is very suitable for a young lady!
- [missing scan tool] awvs, appscan download and installation (with network disk link)
- paramiko下载大文件出错问题 sftp
- 5.3 binary tree_ Code implementation of optimized heap and Top-k problem
- 5.4 binary tree_ Code implementation of various traversal and calculation
- Record: com mysql. cj. jdbc. exceptions. CommunicationsException: Communications link failure... [effective through personal test]
- Record: 1221 - incorrect usage of Union and order by [effective through personal test]
- CLIP学习笔记
- [force deduction] backtracking 1 - Foundation + combination
- What role does cloud computing play in building intelligence?
- Abstract - the shortest novel of 2016
- Fiddler packet capture guide 05: breaking points
- SAP:SWITCH用法
- AD7606/AD7616使ZYNQ在能源电力领域如虎添翼,可实现16/32/64通道AD同步采样
- AM57x 多核SoC开发板——GPMC的多通道AD采集综合案例手册(上)
- 【日常训练】面试题 01.05. 一次编辑
- 【日常训练】384. 打乱数组
- AM57x 多核SoC开发板——GPMC的多通道AD采集综合案例手册(下)
- EDA technology and market analysis
- libmodus源码解读
- 一招win7 c盘瘦身
- Day 1:轮转数组
- 美团四大名著为什么不是三或五
- 是能力更是文化,談談IT系統的安全發布
- C'est la capacité, c'est la culture.
- Am57x multi-core SoC development board -- GPMC's comprehensive case manual for multi-channel AD acquisition (Part 2)
- [daily training] 384 Scramble array
- [daily training] interview question 01.05 One edit
- Am57x multi-core SoC development board -- GPMC's comprehensive case manual for multi-channel AD acquisition (Part I)
- Ad7606 / ad7616 make zynq more powerful in the field of energy and power, and can realize 16 / 32 / 64 channel ad synchronous sampling