asset modules资源模块,可以引入除了js、json【这两种文件可以直接引入】以外的任何的其他类型资源
允许我们应用webpack来打包其他的资源文件,比如字体文件、图标文件。
资源模块类型:asset module type,会通过四种新的类型模块来替换所有的loader
asset/resource:会发送一个单独的文件并导出URL
asset/inline:会导出一个资源的Data URI
asset/source:会导出资源的源代码
asset:会在导出一个Data URI 和发送一个单独的文件之间自动进行选择【inline/resource】
output: {
filename:'bundle.js',
path: path.resolve(__dirname, './dist'),
clean: true,
// 优先级比gennerator低,[contenthash]表示以内容哈希命名,ext表示读取的后缀名
assetModuleFilename: 'images/[contenthash][ext]'
},
module:{
rules:[
{
// 正则表达式,以【.】需要转义,以png结尾
test:/\.png$/,
type:'asset/resource',
// 优先级更高
generator:{
filename:'/images/[contenthash][ext]'
}
}
]
}
四种模块
module:{
rules:[
// 会创建资源
{
test:/\.png$/,
type:'asset/resource',
// 优先级更高
generator:{
filename:'images/[contenthash][ext]',
}
},
// base64,会不创建资源,而是生成base64的链接
{
test:/\.svg$/,
type:'asset/inline',
},
{
test:/\.txt$/,
type:'asset/source',
},
// 当加载的资源大于8kb时,会加载为assets/resource,小于8kb时加载为assets/inline
test:/\.jpg$/,
type:'asset',
parser:{
dataUrlCondition: {
maxSize:4*1024*1024,
}
}
]
}
import helloWorld from './hello-world'
import imgsrc from './assets/aijiang.png'
import unvisitedSvg from './assets/unvisited.svg'
import testTxt from './assets/test.txt'
import blueJpg from './assets/blue.jpg'
helloWorld();
const img = document.createElement('img');
img.src = imgsrc;
document.body.appendChild(img);
const img2 = document.createElement('img');
img2.style.cssText = "width:50px;height:50px;"
img2.src = unvisitedSvg;
document.body.appendChild(img2);
const block = document.createElement('div');
block.style.cssText = "width:200px; height:200px;background:pink;"
block.textContent = testTxt;
document.body.appendChild(block);
const img3 = document.createElement('img');
img3.style.cssText = "width:600px;height:300px;"
img3.src = blueJpg;
document.body.appendChild(img3);