Tabla de contenido
-
-
- Implementar un solo archivo como paquete de archivos js de entrada
- Empaquete varios archivos js en el html especificado y pruebe el empaquetado de entradas múltiples (puntos clave)
- Configure el complemento clean-webpack-plugin para borrar los últimos archivos empaquetados antes de cada paquete.
- Aprenda el empaquetado CSS (no presentaré menos scss pero el funcionamiento es similar)
- Degradar la sintaxis de es6 es7 en archivos js
-
node 版本 14.18.3
webpack5+
//具体packjson 文件
{
"name": "webpack_vue_cli",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack --progress --config ./build/webpack.config.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.18.2",
"@babel/polyfill": "^7.12.1",
"@babel/preset-env": "^7.18.2",
"autoprefixer": "^10.4.7",
"babel-loader": "^8.2.5",
"clean-webpack-plugin": "^4.0.0",
"css-loader": "^6.7.1",
"extract-text-webpack-plugin": "^4.0.0-beta.0",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^5.5.0",
"less": "^4.1.2",
"less-loader": "^11.0.0",
"mini-css-extract-plugin": "^2.6.0",
"postcss-loader": "^7.0.0",
"style-loader": "^3.3.1",
"webpack": "^5.72.1",
"webpack-cli": "^4.9.2"
}
}
// npm init 后 可以直接copy 到本地 再 npm i 下载包
Implementar un solo archivo como paquete de archivos js de entrada
Primero cree la carpeta src y cree un archivo main.js
Cree otro archivo de compilación para almacenar el archivo de configuración del paquete web
const path = require('path');
module.exports={
mode:'development',// 用于指定当前的构建环境 production development none
entry: {
name:path.resolve(__dirname,'../src/main.js')
},
output:{
filename:'output.js',// 打包后的文件名
path: path.resolve(__dirname,'../dist')//打包后的目录
}
}
npm ejecutar ejecución de compilación
Empaquete varios archivos js en el html especificado y pruebe el empaquetado de entradas múltiples (puntos clave)
Utilizando principalmente el complemento html-webpack-plugin
Cree una plantilla HTML pública (todos los archivos HTML de salida posteriores se basan en esta plantilla)
Cree una carpeta pública en el directorio raíz y luego cree 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">
<!-- 配合webpack-html-plugin 设置 title-->
<title><%= htmlWebpackPlugin.options.title %></title>
</head>
<body>
<div>我是统一模板</div>
</body>
</html>
Modificar el archivo de configuración del paquete web
const path = require('path');
const {
CleanWebpackPlugin} = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports={
mode:'development',
//打包入口 可以是多个js 文件
entry:{
main: path.resolve(__dirname,'../src/main.js'),
search: path.resolve(__dirname,'../src/search.js')
},
// js打包文件 输出的位置
output:{
path: path.resolve(__dirname,'../dist'),
filename: 'js/[name].[hash:8].js'
},
plugins:[
//new CleanWebpackPlugin(),//每次打包都清楚之前的打包文件
//定义多个html打包文件
new HtmlWebpackPlugin({
template: path.resolve(__dirname,'../public/index.html'),//入口模板文件
title:'main',//文档标题
filename:'main.html',//html 名称
inject:true, //默认为 true 打包的 script 标签带上 defer
chunks:['main'],// 指定要打包的js 文件 不配置就会把entry 中所有的js 文件全部打包到 html 中
}),
new HtmlWebpackPlugin({
template: path.resolve(__dirname,'../public/index.html'),//入口模板文件
title:'search',//文档标题
filename:'search.html',//html 名称
inject:true, //默认为 true 打包的 script 标签带上 defer
chunks:['search'],
}),
]
}
reempaquetar
Configure el complemento clean-webpack-plugin para borrar los últimos archivos empaquetados antes de cada paquete.
más fácil
Aprenda el empaquetado CSS (no presentaré menos scss pero el funcionamiento es similar)
El
cargador de estilos del complemento utilizado empaquetará el archivo css en la etiqueta de estilo en la etiqueta head y
recuperará el archivo css introducido por el archivo js.
Cree una nueva carpeta css en el directorio src
base.css
div{
width: 100px;
height:100px;
background: red;
}
principal.css
div{
background: blue;
}
búsqueda.css
div{
background: yellow;
}
En main.js y search.js importan
import './css/base.css'
import './css/main.css'
console.log('webpack 个人练习生');
const fn = ()=>{
console.log(2222);
}
fn()
let map = new Map();
let p1 = new Promise((resolve)=>{
resolve(2222)
});
console.log(map,p1);
------
import './css/base.css'
import './css/search.css'
console.log('我是search====');
Modificar el archivo de configuración
y volver a empaquetar
Efecto
Empaquete el CSS introducido en cada archivo js en un archivo CSS para su salida (énfasis)
El complemento MiniCssExtract debe usarse en webpack5
Necesidad de modificar el archivo de configuración.
const path = require('path');
const {
CleanWebpackPlugin} = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractplugin = require('mini-css-extract-plugin')
module.exports={
mode:'development',
//打包入口 可以是多个js 文件
entry:{
main: path.resolve(__dirname,'../src/main.js'),
search: path.resolve(__dirname,'../src/search.js')
},
// js打包文件 输出的位置
output:{
path: path.resolve(__dirname,'../dist'),
filename: 'js/[name].[hash:8].js'
},
module:{
rules:[
{
test:/\.css$/i,//打包 css文件
use:[
{
loader: MiniCssExtractplugin.loader,
}
,'css-loader'] //导入到html style 标签中
}
]
},
plugins:[
new MiniCssExtractplugin({
filename:'css/[name].[hash:8].css',
chunkFilename:'[id].css'
}),
new CleanWebpackPlugin(),//每次打包都清楚之前的打包文件
//定义多个html打包文件
new HtmlWebpackPlugin({
template: path.resolve(__dirname,'../public/index.html'),//入口模板文件
title:'main',//文档标题
filename:'main.html',//html 名称
inject:true, //默认为 true 打包的 script 标签带上 defer
chunks:['main'],// 指定要打包的js 文件 不配置就会把entry 中所有的js 文件全部打包到 html 中
}),
new HtmlWebpackPlugin({
template: path.resolve(__dirname,'../public/index.html'),//入口模板文件
title:'search',//文档标题
filename:'search.html',//html 名称
inject:true, //默认为 true 打包的 script 标签带上 defer
chunks:['search'],
}),
]
}
reempaquetar
Degradar la sintaxis de es6 es7 en archivos js
Complemento dependiente babel-loader @babel/preset-env @babel/core
Modificar archivo de configuración
const path = require('path');
const {
CleanWebpackPlugin} = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractplugin = require('mini-css-extract-plugin')
module.exports={
mode:'development',
//打包入口 可以是多个js 文件
entry:{
main: path.resolve(__dirname,'../src/main.js'),
search: path.resolve(__dirname,'../src/search.js')
},
// js打包文件 输出的位置
output:{
path: path.resolve(__dirname,'../dist'),
filename: 'js/[name].[hash:8].js'
},
module:{
rules:[
{
test:/\.css$/i,//打包 css文件
use:[
{
loader: MiniCssExtractplugin.loader,
}
,'css-loader'] //导入到html style 标签中
},
{
test:/\.js$/i,// 匹配.js结尾的文件
use:{
loader:'babel-loader',
options:{
presets:["@babel/preset-env"]
}
}
}
]
},
plugins:[
new MiniCssExtractplugin({
filename:'css/[name].[hash:8].css',
chunkFilename:'[id].css'
}),
new CleanWebpackPlugin(),//每次打包都清楚之前的打包文件
//定义多个html打包文件
new HtmlWebpackPlugin({
template: path.resolve(__dirname,'../public/index.html'),//入口模板文件
title:'main',//文档标题
filename:'main.html',//html 名称
inject:true, //默认为 true 打包的 script 标签带上 defer
chunks:['main'],// 指定要打包的js 文件 不配置就会把entry 中所有的js 文件全部打包到 html 中
}),
new HtmlWebpackPlugin({
template: path.resolve(__dirname,'../public/index.html'),//入口模板文件
title:'search',//文档标题
filename:'search.html',//html 名称
inject:true, //默认为 true 打包的 script 标签带上 defer
chunks:['search'],
}),
]
}