如何在CSS或是template中使用图片?在CSS中使用,先安装file-loader:
npm i -D file-loader
安装完成后,在package.json中看到的当前版本:
"file-loader": "^1.1.5"
接着在app.scss中加入下面的样式:
html, body{
height: 100%;
min-height: 100%;
background: url(./images/dog.jpg) center center no-repeat;
}
在src目录下已经新建了一个images的目录,并且有一个dog.jpg图片。
再到webpack.config.js中的新加一个rule来使用file-loader:
{
test: /\.jpg$/,
use: ['file-loader']
}
如果图片格式有很多,可以这么定义test:
test: /\.(png|jpg|gif)$/
重新build下,就可以看到下面的页面:
这样就把图片引入到了CSS中。
把图片引入到template中,在src目录下新建一个index.html:
<!DOCTYPE html>
<html lang=en>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>this is the pug template header </h1>
<h1>Pug - node template engine</h1>
<div class=col id=container>
<p>Get on it!</p>
<p>Pug is a terse and simple templating language with a strong focus on performance and powerful features.</p>
</div>
<img src="./images/dog.jpg"/>
show or not...
</body>
把homepage模板也改成index.html(之前是my-index.pug):
new HtmlWebpackPlugin({
title: 'webpack',
excludeChunks:['anotherPage'],
hash: true,
template: './src/index.html'
})
如果像index.html中直接采用标准的html的格式直接引入图片,控制台会出现这样的error:
dog.jpg Failed to load resource: the server responded with a status of 404 (Not Found)
解决办法是采用EJS 关于EJS可以参考这里
<img src=<%= require("./images/dog.jpg")%>/>
重新build后,就可以看图片被引入到页面当中了:
当执行prot命令时,可以看到在dist目录下生的图片:
可以看到生成的图片的名字是一串hash值,如果想让它保持原来的名字并也是生成images目录下,即最终的目录是这样:dist/images/dog.jpg,需要修改use:
use: ['file-loader?name=[name].[ext]&outputPath=images/']
dist 目录下生成的图片如dog.jpg,它实现上占用的空间会比较大,image-webapck-loader可以去优化这些事情,先去安装这个loader:
$ npm install image-webpack-loader --save-dev
安装完成后的当前版本是:
"image-webpack-loader": "^3.4.2",
然后更新rule:
{
test: /\.(png|jpg|gif)$/,
use: [
'file-loader?name=[name].[ext]&outputPath=images/',
'image-webpack-loader'
]
}
注意的是image-webpack-loader要放在file-loader的后面,顺序不能倒,先执行image-webpack-loader进行图片的优化后再通过file-loader save到指定的目录下。
在安装image-webapck-loader的过程出现了错误提示信息,虽然image-webpack-loader安装成功了:
➜ WebPack110 npm i -D image-webpack-loader
> cwebp-bin@3.2.0 postinstall /Users/Stan/Desktop/WebPack110/node_modules/cwebp-bin
> node lib/install.js
✔ cwebp pre-build test passed successfully
> gifsicle@3.0.4 postinstall /Users/Stan/Desktop/WebPack110/node_modules/gifsicle
> node lib/install.js
✔ gifsicle pre-build test passed successfully
&g