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

Vite 5.4.19构建项目时遇pg-cloudflare依赖解析失败、Node.js内置模块外部化问题,配置external后仍报错的解决咨询

Vite 5.4.19构建项目时遇pg-cloudflare依赖解析失败、Node.js内置模块外部化问题,配置external后仍报错的解决咨询

Hey there, let's break down what's going on here and how to fix it step by step:

First, why are these errors happening?

The core issue is your frontend project is trying to bundle pg (a PostgreSQL client built for Node.js/Cloudflare Workers) and its dependencies—tools that aren’t designed to run in regular browser environments:

  1. fs/stream externalized errors: These are Node.js built-in modules that don’t exist in browsers. Vite automatically excludes them from browser builds to avoid runtime crashes.
  2. cloudflare:sockets resolve failure: This is a Cloudflare Workers-only module—it doesn’t exist in standard browsers or Node.js setups.
  3. Bare specifier error after externalizing: When you add pg-cloudflare to external, Vite expects that module to be available at runtime, but browsers have no way to resolve it, hence the error.

Frontend apps shouldn’t connect directly to databases (it’s a huge security risk!), so if your code doesn’t actually use PostgreSQL functionality, we can mock the problematic modules to get the build working:

  1. Create an empty mock module
    Make a new file at src/mocks/empty-module.js:

    // Empty mock for Node.js/Cloudflare-specific modules
    export default {};
    // Add specific exports here if your code tries to access them (e.g., export const Client = () => {};)
    
  2. Update your vite.config.mts to redirect problematic imports
    Modify the resolve.alias section to point incompatible modules to your mock:

    import { PluginOption, defineConfig } from "vite";
    import react from "@vitejs/plugin-react";
    import path from "node:path";
    import { visualizer } from "rollup-plugin-visualizer";
    import svgr from "vite-plugin-svgr";
    import wasm from "vite-plugin-wasm";
    import topLevelAwait from "vite-plugin-top-level-await";
    
    export default defineConfig({
      plugins: [
        react(),
        svgr({
          svgrOptions: {},
          include: "**/*.svg?react",
        }),
        topLevelAwait(),
        wasm(),
        visualizer({
          gzipSize: true,
          brotliSize: true,
          emitFile: false,
          filename: "test.html",
          open: true,
        }) as PluginOption,
      ],
      define: {
        "process.env": process.env,
      },
      css: {},
      optimizeDeps: {
        exclude: ["pg", "pg-cloudflare"],
      },
      build: {
        outDir: "build",
        sourcemap: "hidden",
        rollupOptions: {
          output: {
            sourcemapExcludeSources: false,
            manualChunks: {
              react: ["react", "react-router-dom", "react-dom"],
              reddwarf: ["rd-component", "rdjs-wheel"],
            },
          },
          // Remove the external entries for pg/pg-cloudflare—we're using aliases instead
        },
      },
      resolve: {
        alias: {
          "@": path.resolve(__dirname, "src"),
          "~bootstrap": path.resolve(__dirname, "node_modules/bootstrap"),
          // Redirect incompatible modules to our mock
          "pg": path.resolve(__dirname, "src/mocks/empty-module.js"),
          "pg-cloudflare": path.resolve(__dirname, "src/mocks/empty-module.js"),
          "cloudflare:sockets": path.resolve(__dirname, "src/mocks/empty-module.js"),
        },
      },
      server: {
        proxy: {
          "/tex": {
            target: "https://tex.example.top",
            changeOrigin: true,
          },
          "/infra": { target: "https://your-infra-url-here" }, // Fill in your actual target
        },
      },
    });
    

Solution 2: If you’re targeting Cloudflare Pages/Workers

If your project is meant to run on Cloudflare’s platform (not a regular browser), adjust Vite to recognize Cloudflare’s environment:

  1. Install the Cloudflare Vite plugin:
    pnpm add -D @vitejs/plugin-cloudflare-workers
    
  2. Update your config to use the plugin and mark Cloudflare-specific modules as external:
    import cloudflareWorkers from '@vitejs/plugin-cloudflare-workers';
    
    export default defineConfig({
      plugins: [
        react(),
        cloudflareWorkers(),
        // ... other plugins
      ],
      build: {
        rollupOptions: {
          external: ["cloudflare:sockets"],
          // ... other rollup settings
        },
      },
    });
    

Solution 3: Clean up your dependency tree

Check if texhub-broadcast (the package pulling in pg) is actually needed in your frontend:

  • If it’s a backend-only library, move it to devDependencies or remove it from your frontend project.
  • Reach out to the texhub-broadcast maintainers to see if there’s a browser-compatible version that doesn’t include pg.

Final Note

Frontend apps should never directly include database clients like pg—all database interactions should go through your backend API to keep credentials safe and avoid compatibility issues!

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.08 12:13:08