Q1.1 如何在webpack里 支持 图片/字体 等静态资源
A:
S1 安装 url-loader + file-loader
yarn add url-loader file-loader -D
S2 配置 webpack.config.js,以支持 图片/字体 等静态资源
// .... 其他配置
module: {
rules: [
// 解析图片
// 方法1
// { test: /\.(png|jpg|gif|jpeg)$/, use: 'file-loader' },
// 方法2
{
test: /\.(png|jpg|gif|jpeg)$/,
use: {
loader: 'url-loader',
options: {
limit: 8 * 1024, // 8kb以下的文件会被转换成 base64 格式
}
}
},
// 解析字体
{ test: /\.(woff|woff2|eot|ttf|otf)$/, use: 'file-loader' }
]
}
S3 file-loader/ url-loader 配合 css-loader 用于支持在JS/CSS 中 引入图片
S4 如果需要在 原生HTML中 支持直接引入图片,则需要使用 html-withimg-loader
- 注意,该 loader 已废弃,不推荐使用
- 现在推荐使用 html-loader/ webpack5 内置支持的 asset模块 来替代
Q2.1 如何配置把 js、css、html 单独打包成一个文件
A:
S1 单独生成HTML文件: 使用 HtmlWebpackPlugin 插件
S2 把 图片/CSS 等静态资源 输出到 指定目录
- 把依赖的图片单独 输出到指定目录
- 配置 url-loader/ file-loader 的 outputPath 选项
- 把依赖的CSS单独 输出到指定目录
- 使用 MiniCssExtractPlugin 插件的 filename 选项配置
- 如果想在 静态资源目录前 添加 类似cdn的地址
- 需要使用 publicPath 选项配置
S3 单独生成JS文件: 配置 output.filename 选项
具体实现参考代码见下:
// webpack.config.js 配置
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
// JS类型文件单独 输出到 dist/js 目录下
filename: 'js/[name].[contenthash].js',
// 会在所有类型的资源路径前 添加 该地址
// publicPath:'http://www.xxx.cn'
},
module: {
rules: [
// 解析图片
{
test:/\.(png|jpg|gif)$/,
use:{
loader: 'url-loader',
options:{
limit:1,
outputPath:'/img/',
// 只会在 图片类型的资源路径前 添加 该地址
publicPath:'http://www.cn'
}
}
},
// 解析CSS
{
test: /\.css$/,
use: [
// 把CSS抽出到单独文件
MiniCssExtractPlugin.loader,
'css-loader'
]
}
]
},
plugins: [
// 把独立的CSS 输出到 dist/css 目录下
new MiniCssExtractPlugin({
filename: 'css/[name].[contenthash].css'
}),
// 生成 HTML 文件
new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html'
})
]
};