将图片存储到 Cloudflare 的存储桶中,并通过其提供的公共 URL 来替换代码中的本地路径,可以减小项目中打包的图片文件体积
实现方法的详细步骤:
(1)登录 Cloudflare Dashboard:
(2)配置 R2 存储桶(如果使用 R2):
(3)获取图片的公共链接:
https://.r2.cloudflarestorage.com//home_top_bg.webp
在你的 JS 文件中,修改导入路径,直接使用图片的 Cloudflare URL。例如:
import homeTopBg from "../../images/webp/home_top_bg.webp";
import netHomeTopBg from "../../images/webp/nothome_top_bg.webp";
const homeTopBg = "https://.r2.cloudflarestorage.com//home_top_bg.webp";
const netHomeTopBg = "https://.r2.cloudflarestorage.com//nothome_top_bg.webp";
如果这些图片不是页面初始化时必须加载的资源,可以通过动态导入减少初始加载时间:
const loadImages = async () => {
const homeTopBg = await import("https://.r2.cloudflarestorage.com//home_top_bg.webp");
const netHomeTopBg = await import("https://.r2.cloudflarestorage.com//nothome_top_bg.webp");
};
loadImages();
Cache-Control
指令优化图片的加载性能。如果你希望在 Webpack 配置中直接替换图片路径,可以通过 Webpack 的别名或插件实现:
在 webpack.config.js
中配置:
module.exports = {
resolve: {
alias: {
"@images": "https://.r2.cloudflarestorage.com/",
},
},
};
在代码中:
import homeTopBg from "@images/home_top_bg.webp";
在 webpack.config.js
中添加:
const webpack = require('webpack');
module.exports = {
plugins: [
new webpack.DefinePlugin({
HOME_TOP_BG_URL: JSON.stringify("https://.r2.cloudflarestorage.com//home_top_bg.webp"),
}),
],
};
在代码中使用:
const homeTopBg = HOME_TOP_BG_URL;
Access-Control-Allow-Origin
头部。通过这种方式,将本地大图片替换为 Cloudflare 存储桶中的远程图片,可以有效优化前端项目的加载性能。
参与评论
手机查看
返回顶部