{"slug":"disable-astro-generating-optimized-images","title":"禁用Astro跟弱智一般的静态构建图像优化","description":"折腾了整整一天，终于解决了这傻逼Astro对于静态构建自作聪明的图片优化了，这不仅能提高构建速度，还可以减少无谓的CPU资源消耗，更环保，也更符合Unix哲学","coverImage":"https://b.acofork.com/img/disable-astro-generating-optimized-images-historical-cover.webp","coverWidth":1080,"coverHeight":876,"date":"2025-09-09","tags":["开发"],"pinned":false,"wordCount":1618,"html":"<blockquote>\n<p>视频： <a href=\"https://www.bilibili.com/video/BV12VH2z1EDb\" target=\"_blank\" rel=\"noopener noreferrer\">禁用Astro跟弱智一般的静态构建图像优化_哔哩哔哩_bilibili</a></p>\n</blockquote>\n<h2 id=\"为什么要禁用图片优化\">为什么要禁用图片优化？</h2><p>下图是一个默认的Astro静态构建，也就是 <code>astro build</code> 的输出，输出中记录了每张图片是如何被Astro “优化” 的。我们不难发现问题所在：</p>\n<p>压缩效果微乎其微，甚至有反向压缩。大部分图片仅压缩了几kb，但是为此需要花费 <strong>100-1000ms</strong> 不等，甚至第12行出现了 <code>before: 26kb, after: 28kb</code> 这样的反向压缩</p>\n<p><em>为什么要浪费这么多的时间来进行±10kb左右的图片压缩呢？</em></p>\n<p><img src=\"https://b.acofork.com/img/disable-astro-generating-optimized-images-2025-09-10-06-21-20-26ca667ff5c7024c12d7a8254f483b27.webp\" alt=\"\" width=\"1459\" height=\"632\" loading=\"eager\" decoding=\"async\" /></p>\n<h2 id=\"如何让astro不-优化-图片\">如何让Astro不”优化“图片？</h2><blockquote>\n<p><a href=\"https://docs.astro.build/zh-cn/guides/images/\" target=\"_blank\" rel=\"noopener noreferrer\">图像 | Docs</a></p>\n</blockquote>\n<p>查阅 Astro 文档可知</p>\n<p>会被优化的情况：</p>\n<ul>\n<li><p>非 <code>/public</code> 目录下的图片</p>\n</li>\n<li><p>使用 <code>&lt;Image /&gt;</code> 等Astro图片组件</p>\n</li>\n<li><p>任何MarkDown内的图片，除非你不走Astro内部的 MarkDown -&gt; HTML 转换</p>\n</li>\n</ul>\n<p>不难发现，我们似乎已经找到了一个折中的解决方案： <strong>将图片放置到 /public 目录</strong></p>\n<h2 id=\"尝试将图片放置到-public-目录-不完美\">尝试将图片放置到 /public 目录（不完美）</h2><p>这会遇到一个经典问题，这是我询问 OpenAI ChatGPT 的原话</p>\n<p><em>我遇到了一个两难的问题 我使用Astro 我的文章在./src/content/posts/xxx.md 我的图片之前在./src/contentimg/xxx.webp 由于我不想要Astro默认的图片优化，因为构建太慢了，于是我将图片放到了./img/xxx.webp 然后我将MarkDown引用的图片从 img/xxx.webp 改为了 ./img/xxx.webp 但是现在新的问题出现了，我的MarkText（一个MarkDown编辑器）去寻找了 ./src/content/posts/img/xxx.webp 导致我在编辑器中看不到任何图片 有没有什么好的解决方案？</em></p>\n<p>如果反其道而行之，使用类似 <code>../../img/xxx.webp</code> 会导致部分组件无法获得真实图片，导致 <code>astro build</code> 直接报错退出，比如每篇文章开头的 YAML 元数据中的 <code>image</code> 字段</p>\n<p><strong>结论：</strong> 该方案并不完美。要不无法即写即看，要不构建失败</p>\n<h2 id=\"尝试使用astro官方提供的配置禁用图片优化-失败\">尝试使用Astro官方提供的配置禁用图片优化（失败）</h2><p>遇到Astro上的问题，首先就应该查询官方文档了解是否已有解决方案。通过文档查询，我找到了 <a href=\"https://docs.astro.build/zh-cn/guides/images/#%E9%85%8D%E7%BD%AE-no-op-%E9%80%8F%E4%BC%A0%E6%9C%8D%E5%8A%A1\" target=\"_blank\" rel=\"noopener noreferrer\">图像 | Docs</a> 中的 <strong>配置 no-op 透传服务</strong> ，尝试配置，但是无用，不管是本地运行构建或Cloudflare Worker云端构建，仍然会触发 <strong>generating optimized images</strong> 步骤</p>\n<p><em>如果您了解如何在Astro的配置层面直接禁用图片优化，请联系我！我很乐意与您交流！</em></p>\n<p><img src=\"https://b.acofork.com/img/disable-astro-generating-optimized-images-2025-09-10-06-27-46-image.webp\" alt=\"\" width=\"959\" height=\"599\" loading=\"lazy\" decoding=\"async\" /></p>\n<h2 id=\"尝试直接更改astro源码来禁用图片优化-成功\">尝试直接更改Astro源码来禁用图片优化（成功）</h2><p>研究到这，大半天已经过去了，我已经没有精力去研究怎么 <strong>合法</strong> 禁用Astro的图片优化了，不如单刀直入，直接改源码，使用 <strong>非法操作</strong> 吧</p>\n<p>大致步骤，直接改Astro包的源码，然后用 <code>pnpm patch</code> 为它打个补丁，下面是完整、可用的 <code>astro.patch</code> 。全局禁用图片优化</p>\n<div class=\"markdown-code\" data-language=\"diff\"><div class=\"markdown-code-header\"><span class=\"markdown-code-language\"><svg class=\"code-language-icon\" aria-hidden=\"true\" width=\"16\" height=\"16\" viewbox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z\"></path><path d=\"M14 2v5a1 1 0 0 0 1 1h5\"></path><path d=\"M10 9H8\"></path><path d=\"M16 13H8\"></path><path d=\"M16 17H8\"></path></svg><span>diff</span></span><button type=\"button\" class=\"code-block-copy\" aria-label=\"复制代码\" title=\"复制代码\"><svg class=\"code-block-copy-icon\" aria-hidden=\"true\" width=\"16\" height=\"16\" viewbox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" xmlns=\"http://www.w3.org/2000/svg\"><rect width=\"14\" height=\"14\" x=\"8\" y=\"8\" rx=\"2\" ry=\"2\"></rect><path d=\"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2\"></path></svg></button></div><pre><code class=\"hljs language-diff\"><span class=\"hljs-comment\">diff --git a/dist/assets/utils/transformToPath.js b/dist/assets/utils/transformToPath.js</span>\n<span class=\"hljs-comment\">index cca8548dec42090b0621d1f21c86f503d5bba1be..8b0a3cfcea73abc4d63592709bb9ba2b2f83989a 100644</span>\n<span class=\"hljs-comment\">--- a/dist/assets/utils/transformToPath.js</span>\n<span class=\"hljs-comment\">+++ b/dist/assets/utils/transformToPath.js</span>\n<span class=\"hljs-meta\">@@ -13,7 +13,9 @@</span> function propsToFilename(filePath, transform, hash) {\n   }\n   const prefixDirname = isESMImportedImage(transform.src) ? dirname(filePath) : \"\";\n   let outputExt = transform.format ? `.${transform.format}` : ext;\n<span class=\"hljs-deletion\">-  return decodeURIComponent(`${prefixDirname}/${filename}_${hash}${outputExt}`);</span>\n<span class=\"hljs-addition\">+  </span>\n<span class=\"hljs-addition\">+  // Force disable image optimization - return original path without hash and format conversion</span>\n<span class=\"hljs-addition\">+  return decodeURIComponent(`${prefixDirname}/${filename}${ext}`);</span>\n }\n function hashTransform(transform, imageService, propertiesToHash) {\n   const hashFields = propertiesToHash.reduce(\n<span class=\"hljs-comment\">diff --git a/dist/core/build/generate.js b/dist/core/build/generate.js</span>\n<span class=\"hljs-comment\">index 3144f4c058b161b9e6eb3c8d891b743b34783653..0ba275b320204e154307c6aff75452e9dcb2300d 100644</span>\n<span class=\"hljs-comment\">--- a/dist/core/build/generate.js</span>\n<span class=\"hljs-comment\">+++ b/dist/core/build/generate.js</span>\n<span class=\"hljs-meta\">@@ -91,7 +91,8 @@</span> ${bgGreen(black(` ${verb} static routes `))}`);\n `)\n   );\n   const staticImageList = getStaticImageList();\n<span class=\"hljs-deletion\">-  if (staticImageList.size) {</span>\n<span class=\"hljs-addition\">+  // Force disable image optimization - hardcoded</span>\n<span class=\"hljs-addition\">+  if (false) {</span>\n     logger.info(\"SKIP_FORMAT\", `${bgGreen(black(` generating optimized images `))}`);\n     const totalCount = Array.from(staticImageList.values()).map((x) =&gt; x.transforms.size).reduce((a, b) =&gt; a + b, 0);\n     const cpuCount = os.cpus().length;</code></pre></div><p>下文为我让OpenAI ChatGPT 5解释的已经禁用图片优化的补丁（<code>astro.patch</code>）具体做了什么</p>\n<h4 id=\"修改点-1-dist-assets-utils-transformtopath-js\">修改点 1：<code>dist/assets/utils/transformToPath.js</code></h4><div class=\"markdown-code\" data-language=\"diff\"><div class=\"markdown-code-header\"><span class=\"markdown-code-language\"><svg class=\"code-language-icon\" aria-hidden=\"true\" width=\"16\" height=\"16\" viewbox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z\"></path><path d=\"M14 2v5a1 1 0 0 0 1 1h5\"></path><path d=\"M10 9H8\"></path><path d=\"M16 13H8\"></path><path d=\"M16 17H8\"></path></svg><span>diff</span></span><button type=\"button\" class=\"code-block-copy\" aria-label=\"复制代码\" title=\"复制代码\"><svg class=\"code-block-copy-icon\" aria-hidden=\"true\" width=\"16\" height=\"16\" viewbox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" xmlns=\"http://www.w3.org/2000/svg\"><rect width=\"14\" height=\"14\" x=\"8\" y=\"8\" rx=\"2\" ry=\"2\"></rect><path d=\"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2\"></path></svg></button></div><pre><code class=\"hljs language-diff\"><span class=\"hljs-deletion\">-  return decodeURIComponent(`${prefixDirname}/${filename}_${hash}${outputExt}`);</span>\n<span class=\"hljs-addition\">+  </span>\n<span class=\"hljs-addition\">+  // Force disable image optimization - return original path without hash and format conversion</span>\n<span class=\"hljs-addition\">+  return decodeURIComponent(`${prefixDirname}/${filename}${ext}`);</span></code></pre></div><h5 id=\"原逻辑\">原逻辑</h5><ul>\n<li><p>原本的返回路径是：</p>\n<div class=\"markdown-code\" data-language=\"bash\"><div class=\"markdown-code-header\"><span class=\"markdown-code-language\"><svg class=\"code-language-icon\" aria-hidden=\"true\" width=\"16\" height=\"16\" viewbox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M12 19h8\"></path><path d=\"m4 17 6-6-6-6\"></path></svg><span>bash</span></span><button type=\"button\" class=\"code-block-copy\" aria-label=\"复制代码\" title=\"复制代码\"><svg class=\"code-block-copy-icon\" aria-hidden=\"true\" width=\"16\" height=\"16\" viewbox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" xmlns=\"http://www.w3.org/2000/svg\"><rect width=\"14\" height=\"14\" x=\"8\" y=\"8\" rx=\"2\" ry=\"2\"></rect><path d=\"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2\"></path></svg></button></div><pre><code class=\"hljs language-bash\">{prefixDirname}/{filename}_{<span class=\"hljs-built_in\">hash</span>}.{format or ext}</code></pre></div><ul>\n<li><p><code>prefixDirname</code>：如果图片是通过 ESM import 进来的，会带上所在目录，否则为空。</p>\n</li>\n<li><p><code>filename</code>：文件名。</p>\n</li>\n<li><p><code>hash</code>：基于图片参数生成的 hash，用于区分不同尺寸/格式。</p>\n</li>\n<li><p><code>outputExt</code>：可能是 <code>webp</code>、<code>avif</code> 等格式。</p>\n</li>\n</ul>\n</li>\n</ul>\n<p>👉 这样 Astro 会给图片文件生成带 hash 的路径，并且可能修改格式。</p>\n<h5 id=\"修改后逻辑\">修改后逻辑</h5><ul>\n<li>返回路径改成了：</li>\n</ul>\n<div class=\"markdown-code\" data-language=\"bash\"><div class=\"markdown-code-header\"><span class=\"markdown-code-language\"><svg class=\"code-language-icon\" aria-hidden=\"true\" width=\"16\" height=\"16\" viewbox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M12 19h8\"></path><path d=\"m4 17 6-6-6-6\"></path></svg><span>bash</span></span><button type=\"button\" class=\"code-block-copy\" aria-label=\"复制代码\" title=\"复制代码\"><svg class=\"code-block-copy-icon\" aria-hidden=\"true\" width=\"16\" height=\"16\" viewbox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" xmlns=\"http://www.w3.org/2000/svg\"><rect width=\"14\" height=\"14\" x=\"8\" y=\"8\" rx=\"2\" ry=\"2\"></rect><path d=\"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2\"></path></svg></button></div><pre><code class=\"hljs language-bash\">{prefixDirname}/{filename}{ext}</code></pre></div><ul>\n<li>直接使用原始扩展名，不带 hash，也不做格式转换。</li>\n</ul>\n<p>✅ 作用：完全禁用图片优化的文件名规则，保留原始文件路径。</p>\n<hr />\n<h4 id=\"修改点-2-dist-core-build-generate-js\">修改点 2：<code>dist/core/build/generate.js</code></h4><div class=\"markdown-code\" data-language=\"diff\"><div class=\"markdown-code-header\"><span class=\"markdown-code-language\"><svg class=\"code-language-icon\" aria-hidden=\"true\" width=\"16\" height=\"16\" viewbox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z\"></path><path d=\"M14 2v5a1 1 0 0 0 1 1h5\"></path><path d=\"M10 9H8\"></path><path d=\"M16 13H8\"></path><path d=\"M16 17H8\"></path></svg><span>diff</span></span><button type=\"button\" class=\"code-block-copy\" aria-label=\"复制代码\" title=\"复制代码\"><svg class=\"code-block-copy-icon\" aria-hidden=\"true\" width=\"16\" height=\"16\" viewbox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" xmlns=\"http://www.w3.org/2000/svg\"><rect width=\"14\" height=\"14\" x=\"8\" y=\"8\" rx=\"2\" ry=\"2\"></rect><path d=\"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2\"></path></svg></button></div><pre><code class=\"hljs language-diff\"><span class=\"hljs-deletion\">-  if (staticImageList.size) {</span>\n<span class=\"hljs-addition\">+  // Force disable image optimization - hardcoded</span>\n<span class=\"hljs-addition\">+  if (false) {</span></code></pre></div><h5 id=\"原逻辑-2\">原逻辑</h5><ul>\n<li><p><code>staticImageList</code> 存放了 Astro build 时需要优化的所有静态图片。</p>\n</li>\n<li><p>如果有图片，Astro 会启动优化逻辑：</p>\n<ul>\n<li><p>打印日志 <code>\"generating optimized images\"</code></p>\n</li>\n<li><p>遍历 <code>staticImageList</code>，并调用 image service 去生成不同尺寸和格式。</p>\n</li>\n</ul>\n</li>\n</ul>\n<h5 id=\"修改后逻辑-2\">修改后逻辑</h5><ul>\n<li><p>把 <code>if (staticImageList.size)</code> 改成了 <code>if (false)</code>。</p>\n</li>\n<li><p>这意味着 <strong>Astro 永远不会进入优化图片的流程</strong>。</p>\n</li>\n</ul>\n<p>✅ 作用：强制跳过所有图片优化步骤。</p>\n<hr />\n<h4 id=\"总结\">总结</h4><p>你的这个 patch 做了两件事：</p>\n<ol>\n<li><p><strong>绕过文件名 hash 和格式转换</strong> → 保证生成的图片路径就是原始路径。</p>\n</li>\n<li><p><strong>完全禁用构建时图片优化</strong> → Astro build 时不再生成任何衍生格式或多尺寸图片。</p>\n</li>\n</ol>\n<p>等价于 <strong>彻底关闭 Astro 的图片优化功能</strong>，构建出来的就是你原始的图片。</p>\n<h2 id=\"最终效果\">最终效果</h2><p>任何情况下使用 <code>astro build</code> 都会跳过图片优化，Cloudflare Worker的构建时间从 3分钟下降到2分钟</p>\n<p><img src=\"https://b.acofork.com/img/disable-astro-generating-optimized-images-2025-09-10-06-46-49-image.webp\" alt=\"\" width=\"331\" height=\"63\" loading=\"lazy\" decoding=\"async\" /></p>\n<p><img src=\"https://b.acofork.com/img/disable-astro-generating-optimized-images-2025-09-10-06-47-01-image.webp\" alt=\"\" width=\"341\" height=\"65\" loading=\"lazy\" decoding=\"async\" /></p>\n<p>构建后的页面不再为全局webp，透传原始文件名、扩展名。但仍然保留了 <code>/_astro</code> 路径，依旧支持相对路径粘贴图片</p>\n<p><img src=\"https://b.acofork.com/img/disable-astro-generating-optimized-images-d836b41fd85611972c2086a7064705bdb1b4ff7c.webp\" alt=\"\" width=\"545\" height=\"34\" loading=\"lazy\" decoding=\"async\" /></p>\n<p><img src=\"https://b.acofork.com/img/disable-astro-generating-optimized-images-ff1314b1ab7d60bd9a49d6499db22cde23fb9f60.webp\" alt=\"\" width=\"478\" height=\"26\" loading=\"lazy\" decoding=\"async\" /></p>\n","toc":[{"id":"为什么要禁用图片优化","text":"为什么要禁用图片优化？","depth":2},{"id":"如何让astro不-优化-图片","text":"如何让Astro不”优化“图片？","depth":2},{"id":"尝试将图片放置到-public-目录-不完美","text":"尝试将图片放置到 /public 目录（不完美）","depth":2},{"id":"尝试使用astro官方提供的配置禁用图片优化-失败","text":"尝试使用Astro官方提供的配置禁用图片优化（失败）","depth":2},{"id":"尝试直接更改astro源码来禁用图片优化-成功","text":"尝试直接更改Astro源码来禁用图片优化（成功）","depth":2},{"id":"修改点-1-dist-assets-utils-transformtopath-js","text":"修改点 1：dist/assets/utils/transformToPath.js","depth":4},{"id":"原逻辑","text":"原逻辑","depth":5},{"id":"修改后逻辑","text":"修改后逻辑","depth":5},{"id":"修改点-2-dist-core-build-generate-js","text":"修改点 2：dist/core/build/generate.js","depth":4},{"id":"原逻辑-2","text":"原逻辑","depth":5},{"id":"修改后逻辑-2","text":"修改后逻辑","depth":5},{"id":"总结","text":"总结","depth":4},{"id":"最终效果","text":"最终效果","depth":2}]}