You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Cloudflare Pages构建Astro SSR博客时遭遇Node.js stream打包错误

解决Cloudflare Pages上Astro SSR构建失败:Cannot bundle Node.js built-in "stream"

问题原因

构建失败是因为reading-time@1.5.0依赖了Node.js内置的stream模块,而Vite在打包Astro SSR应用时,默认会尝试将所有依赖打包进产物,但Node.js内置模块无法直接被打包到Cloudflare Worker的运行环境中,因此触发错误。

解决方案

方案1:升级reading-time到最新版本

旧版本的reading-time使用了Node.js专属的stream模块,新版本(v2.x及以上)已经移除了该依赖,改用浏览器/Worker兼容的实现。执行以下命令升级:

pnpm upgrade reading-time

或者直接安装指定版本:

pnpm add reading-time@^2.0.0

方案2:配置Vite跳过打包reading-time

如果无法升级依赖,可以修改astro.config.mjs,将reading-time加入ssr.noExternal列表,让Vite不打包该依赖,而是由Cloudflare Worker的Node.js兼容层处理:

import { defineConfig } from 'astro/config';
import cloudflare from '@astrojs/cloudflare';

export default defineConfig({
  output: 'server',
  adapter: cloudflare({}),
  vite: {
    ssr: {
      noExternal: ['reading-time']
    }
  }
});

Cloudflare Worker的Node.js兼容层支持stream模块,因此该依赖可以在运行时正常加载。

方案3:替换为浏览器兼容的阅读时间计算方案

如果以上两种方案都不适用,可以自行实现简单的阅读时间计算逻辑,或者使用无Node内置依赖的替代库。例如,基于文本字数的估算逻辑:

// 示例:计算中文阅读时间(按每分钟400字估算)
export function calculateReadingTime(text) {
  const wordCount = text.replace(/\s/g, '').length;
  return Math.ceil(wordCount / 400);
}

内容的提问来源于stack exchange,提问作者user25019377

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 19:07:32