知识回顾
上一节通过css文件的加载方式学习了在打包过程中如何使用loader加载css文件将其打包到js代码中,主要是使用css-loader将css文件加载解析,然后使用style-loader将其以style标签的形式在html中呈现。只要在js代码中有通过import引入并使用的css都会被正常打包。
file-loader
使用file-loader的方法跟css-loader一样,通过yarn add file-loader --dev局部安装,然后在webpack.config.js添加配置:
```
const path = require('path')
module.exports = {
mode: 'none',
entry: "./src/index.js", //入口文件
output: {
filename: "bundle.js", //文件名称
path: path.join(__dirname, "output"), //输出目录
},
module: {
rules: [
{
test: /\.css$/, //使用正则表达式匹配.css文件
use: ['style-loader','css-loader']
},
{
test: /\.jpg$/, //我添加的图片是jpg格式,所以这里匹配jpg文件
use: 'file-loader'
}
]
}}
```
在index.js中使用添加的图片
```
import createHeading from './heading.js'
import './index.css'
import icon from './guidao.jpg'
const heading = createHeading()
document.body.append(heading)
const img = new Image();
img.src = icon;
document.body.append(img);
```
先来打包看看结果,执行yarn webpack,完了过后执行serve .
打开链接会看到图片并没有显示,右击查看图片会看到图片的链接是在项目根目录下,实际上我们的图片是在outpu目录下的,这是因为webpack会默认以index.html文件的根目录作为网站的根目录,但我们设置的网站根目录是outpu目录,所以我们需要在webpack.config.js中添加一个publicPath属性指定网站根目录
再次打包,执行serve .刷新页面,图片已经可以正常显示了