css-loader
用来读取css文件
像解释import/require()一样解释@import和url(),并解析它们。
配置参数如下:
{
test: /\.css$/i,
loader: "css-loader",
options: {
url: (url, resourcePath) => { // resourcePath - path to css file
// Don't handle `img.png` urls
if (url.includes("img.png")) {
return false;
}
return true;
},
import: (url, media, resourcePath) => {
// Don't handle `style.css` import 如下:
//@import url(./style.css) => require('./style.css')
if (url.includes("style.css")) {//
return false;
}
return true;
},
// Using `local` value has same effect like using `modules: true`
//使用false值可以避免解析CSS模块特性从而提高性能,
//对使用普通CSS的开发人员非常有用
modules: {
compileType: "module",//可选值: 'icss' | 'module'(默认)
mode: "local",//local, global, and pure
auto: true,//允许自动启用基于文件名的css模块
exportGlobals: true,
//允许配置生成的本地ident name 类型:String 默认值:'[hash:base64]'
localIdentName: "[path][name]__[local]--[hash:base64:5]",
//允许为本地ident name重定义基本加载程序上下文。类型:String 默认:compiler.context
localIdentContext: path.resolve(__dirname, "src"),
//允许添加自定义哈希生成更独特的类 默认:undefined
localIdentHashPrefix: "my-custom-hash",
namedExport: true,
exportLocalsConvention: "camelCase",
exportOnlyLocals: false,
}
}
style-loader
用来把<style>标签插入到HTML页面
url-loader
用来把html以及css中的图片打包成base64,但不能编译js中的图片
配置参数如下:
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,//正则匹配图片格式
loader: 'url-loader',//使用"url-loader"加载器
include: [resolve('static'),resolve('src')],//指定对文件夹里面的图片进行url-loader转换
options: {
limit: 100000,//对小于10kb的进行base64转换
name: utils.assetsPath('img/[name].[hash:7].[ext]'),//自定义image的路径和名称
//如果文件大于limit则默认使用file-loader,并将所有查询参数传递给它
fallback: 'responsive-loader'//如不指定 就默认使用file-loader
}
}
小结: 通常对于10kb以下的图片可以通过转化为base64的方式减少资源请求,加快页面渲染速度。但是对于较大尺寸的图片还是推荐请求资源的方式,这是因为大尺寸的图片转化成base64位的字符串比较长,增加代码体积,影响代码的可读性。