一,soucrce-map
1.文件目录结构
2.webpack.config.js配置文件
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const webpack = require("webpack");
const m = 'production'
module.exports = {
entry: {
index: "./src/index.js"
},
output: {
filename: "js/[name].js",
clean: true
},
// mode: 'development',
mode: m, // 启用生产环境
devtool: 'source-map',
plugins: [
new webpack.DefinePlugin({
// 告诉其它JS 有没 有使用生产环境
ENV: JSON.stringify(m === 'production'),
}),
new HtmlWebpackPlugin({
scriptLoading: "blocking"
}),
new MiniCssExtractPlugin({
filename: "css/[name].css"
})
],
module: {
rules: [{
test: /\.hbs$/,
use: ["handlebars-loader"]
}, {
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader"]
}, {
test: /\.(png|jpg|jpeg|svg|gif)$/,
type: "asset/resource",
generator: {
filename: "images/[name][ext][query]"
}
}]
},
}
二,资源压缩(JS,CSS)
所用插件“mini-css-extract-plugin”与“css-minimizer-webpack-plugin”
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
module.exports = {
entry: {
index: "./src/index.js"
},
output: {
filename: "js/[name].js",
clean: true
},
mode: 'production',
optimization: {
minimize: true,
minimizer: [
new CssMinimizerPlugin(),
],
},
plugins: [
new HtmlWebpackPlugin({
scriptLoading: "blocking"
}),
new MiniCssExtractPlugin({
filename: "css/[name].css"
})
],
三,hash与缓存
1.文件目录结构
2.文件代码
(1).webpack.config.js
const HTMLwebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: './src/index.js',
output: {
clean: true,
//filename: '[chunkhash].js'
filename: '[contenthash].js'
},
mode: 'development',
module: {
rules: [
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader,'css-loader']
},
]
},
plugins: [
new HTMLwebpackPlugin({
scriptLoading: 'blocking'
}),
new MiniCssExtractPlugin({
//filename: '[chunkhash].css'
filename: '[contenthash].css'
})
],
}
(2).server.js
const express =require('express');
const app = express();
app.use(express.static('dist',{ maxAge: 1000 * 3600}));
app.listen(8080, () => {
console.log('服务器运行在:http://127.0.0.1:8080')
});
四,插件html-webpack-plugin与多入口打包
1.文件结构
2.webpack.config.js代码
const aa = require('html-webpack-plugin');
module.exports = {
entry:{
a:'./src/index.js',
b:'./src/indexb.js',
},
output:{
clean:true,
filename:'bundle@[name].js'
},
mode:'development',
plugins:[
new aa({
scriptLoading:'blocking',
template:'./src/tpl/a.html',
chunks:['a'],
filename:'./html/a.html'
}),
new aa({
scriptLoading:'blocking',
template:'./src/tpl/b.html',
chunks:['b'],
filename:'./html/b.html'
})
]
}
五,JS文件输出目录设置
{
test:/\.js$/,
exclude:/(node_modules|index)/,
type:'asset/resource',
generator:{
filename:'js[name][ext][query]'
}
},