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

Remix集成googleapis库时出现process未定义错误求助

解决Remix对接Google Calendar时客户端出现process is not defined错误

问题根源

尽管你将Google API逻辑放在了服务端的loader函数中,但Remix的打包机制可能仍会将googleapis及其依赖(如gaxios、google-auth-library)的部分代码注入到客户端包中,而客户端环境不存在Node.js的process变量,因此触发报错。另外,若返回的响应包含服务端专属对象(而非纯可序列化JSON),也可能导致客户端尝试解析时加载不必要的模块。


解决方案步骤

1. 隔离服务端代码,避免客户端打包

使用Remix推荐的server-only包标记服务端专属代码,确保相关模块不会被打包到客户端:

npm install server-only

创建单独的服务端逻辑文件(如app/services/google.server.ts):

import "server-only";
import { google } from "googleapis";

// 封装Google Calendar API调用逻辑
export async function fetchCalendarList() {
  const calendar = google.calendar({ version: "v3" });
  try {
    // 仅返回可序列化的data部分,避免返回包含服务端对象的完整响应
    const response = await calendar.calendarList.list();
    return response.data;
  } catch (error) {
    console.error("获取日历列表失败:", error);
    throw error;
  }
}

2. 修改路由Loader,使用隔离的服务端逻辑

在路由文件中导入上述服务端函数,确保Loader仅处理数据获取和返回:

import { json, LoaderArgs } from "@remix-run/node";
import { fetchCalendarList } from "~/services/google.server";
import { Link } from "@remix-run/react";

export async function loader({}: LoaderArgs) {
  try {
    const calendarList = await fetchCalendarList();
    return json({ calendarList });
  } catch (error) {
    return json({ error: "获取日历列表失败" }, { status: 500 });
  }
}

const Index = () => {
  return (
    <>
      <h1>Welcome</h1>
      <Link to="/login">Login</Link>
    </>
  );
};

export default Index;

3. 配置构建工具注入process变量

根据你的Remix项目类型(Vite或Webpack),添加对应配置:

若使用Remix Vite

修改vite.config.ts,注入空的process.env对象:

import { vitePlugin as remix } from "@remix-run/dev";
import { defineConfig } from "vite";

export default defineConfig({
  plugins: [remix()],
  define: {
    "process.env": {},
  },
});
若使用传统Webpack的Remix项目

修改remix.config.js,添加Webpack配置:

/** @type {import('@remix-run/dev').AppConfig} */
export default {
  serverModuleFormat: "cjs",
  webpack: (config) => {
    // 为客户端提供process的浏览器兼容实现
    config.resolve.fallback = {
      ...config.resolve.fallback,
      process: require.resolve("process/browser"),
    };
    // 注入process.env变量
    config.plugins.push(
      new require("webpack").DefinePlugin({
        "process.env": JSON.stringify(process.env),
      })
    );
    return config;
  },
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 07:04:56