引入图片
客户端负责生成文件
引入图片
jsx
import imgSrc from "@/assets/index.png";
export default function () {
return <img src={imgSrc} alt="img" />;
}webpack 配置
bash
yarn add file-loader -D- file-loader: 用于处理文件
js
// webpack/webpack.client.js
module.exports = {
// ..
module: {
// ..
rules: [
{
test: /\.(png)|(jpg)$/,
use: {
loader: "file-loader",
options: {
name: "img/[name].[hash:5].[ext]", // 输出路径,public/img/xxx.png
},
},
},
],
},
};服务端保证图片路径一致
webpack 配置
js
// webpack/webpack.server.js
module.exports = {
// ..
module: {
// ..
rules: [
{
test: /\.(png)|(jpg)$/,
use: {
loader: "file-loader",
options: {
name: "img/[name].[hash:5].[ext]", // 输出路径,public/img/xxx.png
emitFile: false, // 不输出图片文件
},
},
},
],
},
};css 中图片
css
.img-container {
background-image: url("../../assets/index.png");
background-position: center;
background-size: cover;
height: 300px;
width: 300px;
}webpack 配置文件
js
// webpack/webpack.base.js
module.exports = {
// ..
output: {
publicPath: "/", // 输出路径
},
};