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

Shopify结账UI扩展导入外部模块时遇“window is not defined”错误

Shopify结账UI扩展导入外部模块报错:window is not defined

问题背景

在新版Shopify结账UI扩展的src/Checkout.tsx中导入@shoprunner/shopping模块时,抛出ReferenceError: window is not defined错误。已在shopify.ui.extension.toml中开启network_access = true,尝试过异步延迟加载模块,但未解决问题。

错误根源

Shopify结账UI扩展运行在隔离执行环境中,没有原生浏览器的window全局对象,而@shoprunner/shopping模块在初始化阶段直接访问了window,导致报错。

解决方案

1. 组件挂载后动态加载模块+模拟window对象

利用React的useEffect钩子在组件挂载后加载模块,同时为模块提供模拟的window对象:

import { useEffect, useState } from 'react';

const CheckoutExtension = () => {
  const [shoppingModule, setShoppingModule] = useState<null | any>(null);

  useEffect(() => {
    const loadModule = async () => {
      try {
        // 为模块提供模拟的window对象(适配Shopify隔离环境)
        if (typeof window === 'undefined') {
          (globalThis as any).window = globalThis;
        }
        // 动态导入外部模块
        const module = await import('https://assets.prd.shoprunner.io/@shoprunner/shopping@1/es6/index.js');
        setShoppingModule(module);
      } catch (error) {
        console.error('模块加载失败:', error);
      }
    };

    loadModule();
  }, []);

  if (!shoppingModule) {
    return <div>加载中...</div>;
  }

  // 在这里使用模块功能
  return <div>扩展内容</div>;
};

export default CheckoutExtension;

2. 查找模块的无依赖版本

检查@shoprunner/shopping的官方文档,确认是否提供不依赖浏览器window的版本(如UMD格式、Node.js兼容版),替换当前导入的ES6版本。

3. 替换window相关API为Shopify提供的能力

如果模块仅依赖window的部分API(如fetch),可以改用Shopify扩展内置的网络能力,或通过useShop钩子获取上下文替代。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 20:50:00