主题
打包结构控制
js
module.exports = {
output: {
// 每个输出 bundle 的名称
filename: '[name].js',
// 输出目录
path: path.resolve(__dirname, 'dist'),
// 静态资源路径前缀
publicPath: '/',
},
}
资源文件:
js
module.exports = {
module: {
rules: [
{
test: /\.(png|jpg|gif)$/, // 匹配图片文件
use: [
{
loader: 'url-loader',
options: {
limit: 8192, // 小于 8KB 的文件转为 base64
name: 'assets/[name].[hash].[ext]', // 输出路径和文件名
},
},
],
},
],
},
}
url-loader
:将小文件转为 base64,减少 HTTP 请求。file-loader
:将文件复制到输出目录,并返回文件路径。
生成 HTML 文件:
js
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html', // 模板文件
filename: 'index.html', // 输出文件名
}),
],
}
提取 CSS 到单独文件:
js
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
plugins: [
new MiniCssExtractPlugin({
filename: '[name].[contenthash].css', // 输出文件名
}),
],
module: {
rules: [
{
test: /\.css$/, // 匹配 CSS 文件
use: [MiniCssExtractPlugin.loader, 'css-loader'],
},
],
},
}