# @gadgetinc/react-shopify-app-bridge 中文文档

规范地址：https://npmcn.com/package/%40gadgetinc/react-shopify-app-bridge/

版本：0\.21\.4
npm 元数据更新时间：2026-03-30T18:47:11.989Z
中文译文更新时间：2026-11-15T20:51:23.789Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40gadgetinc/react-shopify-app-bridge
原文对照：https://npmcn.com/package/%40gadgetinc/react-shopify-app-bridge/?lang=original
项目主页：https://github.com/gadget-inc/js-clients/tree/main/packages/react-shopify-app-bridge
源码仓库：https://github.com/gadget-inc/js-clients

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：99 kB，22 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：4 个
- peer 依赖：@gadgetinc/core \>=0\.15\.1，react ^19\.0\.0，react-dom ^19\.0\.0
- 首次发布：2022-06-02T19:33:16.557Z
- 最新版本发布：2026-03-30T18:47:11.792Z
- 近 30 天下载量：17878（2026-10-16 至 2026-11-14，npm 官方下载统计）
- 已发布版本数：73（近 12 个月 6 个）

## 中文简介

![Gadget logo](https://raw.githubusercontent.com/gadget-inc/js-clients/main/docs/assets/gadget-logo.png)

## 安装

```sh
npm install @gadgetinc/react-shopify-app-bridge
```

也可以使用：`pnpm add @gadgetinc/react-shopify-app-bridge`、`yarn add @gadgetinc/react-shopify-app-bridge`、`bun add @gadgetinc/react-shopify-app-bridge`

## README

![Gadget logo](https://raw.githubusercontent.com/gadget-inc/js-clients/main/docs/assets/gadget-logo.png)

 ![GitHub CI status](https://badgen.net/github/checks/gadget-inc/js-clients/main/test?label=CI)[![npm version](https://badgen.net/npm/dw/@gadgetinc/react-shopify-app-bridge?color=4148f2)](https://www.npmjs.com/package/@gadgetinc/react-shopify-app-bridge)

**与 Shopify 嵌入式应用程序开发一起使用的反钩和组件 [游戏](https://gadget.dev/) 平台.**

## 特征

该图书馆具有以下功能:

-   自动启动 OAuth 进程, 使用 Gadget 程序的新用户, 必要时逃离 Shopify 的 iframe
-   使用 Gadget OAuth PKCE 与 Gadget 后端建立 ifram 安全会话
-   为 Gadget 使用后端调用设置正确的反应上下文 `@gadgetinc/react`

## 安装

这是为您的 Gadget app 生成的 JavaScript 客户端软件包的配套软件包 。 您必须先为您的应用程序安装 JS 客户端, 然后安装此软件包 .

要为您的应用程序安装JS客户端, 您必须建立 Gadget 国家防范机制注册, 然后安装客户端 :

```bash
npm config set @gadget-client:registry https://registry.gadget.dev/npm

yarn add @gadget-client/my-app-slug
# or
npm install @gadget-client/my-app-slug
```

完整的安装指令可以在 Gadget 文件中找到 `https://docs.gadget.dev/api/<my-app-slug>/external-api-calls/installing`。 。 。 .

一旦您安装了JS客户端,您就可以安装 React shooks 库和 Shopify App 桥库 `yarn` 或者说 `npm`数字 :

```
yarn add @gadgetinc/react-shopify-app-bridge @gadgetinc/react @shopify/app-bridge-react react
# or
npm install --save @gadgetinc/react-shopify-app-bridge @gadgetinc/react @shopify/app-bridge-react react
```

# 目的

在探索 Shopify 嵌入式应用开发时, 您可能已经发现 [文档](https://shopify.dev/apps/tools/app-bridge/getting-started) 关于如何建立 Shopify App Bridge。 这个软件包将照顾到涉及OAuth的所有步骤并启动 Shopify app桥. OAuth步骤以及 Shopify 应用程序桥的初始化由 `Provider`App Bridge的初始实例可通过 `appBridge` 密钥返回自 `useGadget`。 。 。 .

## 示例用途

注: 这个例子与在下列文件中发现的例子非常相类似: [@ gadgetinc/ 反应](https://github.com/gadget-inc/js-clients/tree/main/packages/react)但是,如果您使用 `@gadgetinc/react-shopify-app-bridge` 软件包.

`src/api.ts`

```typescript
// replace `my-app-slug` with your app slug from your Gadget app's domain
import { Client, BrowserSessionStorageType } from "@gadget-client/my-app-slug";

export const api = new Client({
  authenticationMode: {
    browserSession: {
      storageType: BrowserSessionStorageType.Temporary,
    },
  },
});
```

`src/app.tsx`

```tsx
// import Gadget's react hooks for accessing data from your Gadget app
import { useAction, useFindMany } from "@gadgetinc/react";
// import the Gadget<->Shopify bindings that manage the auth process with Shopify
import { AppType, Provider as GadgetProvider, useGadget } from "@gadgetinc/react-shopify-app-bridge";
// import and use Shopify's react components like you might in other Shopify app
import { Button, Redirect, TitleBar } from "@shopify/app-bridge/actions";
// import the instance of the Gadget API client for this app constructed in the other file
import { api } from "./api";

export default function App() {
  return (
    // Wrap our main application's react components in the `<GadgetProvider/>` component to interface with Shopify
    // This wrapper sets up the Shopify App Bridge, and will automatically redirect to perform the OAuth authentication if the shopify shop doesn't yet have the store installed.
    <GadgetProvider type={AppType.Embedded} shopifyApiKey="REPLACE ME with api key from Shopify partners dashboard" api={api}>
      <ProductManager />
    </GadgetProvider>
  );
}

// An example component that uses the Gadget React hooks to work with data in the Shopify backend
function ProductManager() {
  const { loading, appBridge, isRootFrameRequest, isAuthenticated } = useGadget();
  const [, deleteProduct] = useAction(api.shopifyProduct.delete);
  const [{ data, fetching, error }, refresh] = useFindMany(api.shopifyProduct);

  if (error) return <>Error: {error.toString()}</>;
  if (fetching) return <>Fetching...</>;
  if (!data) return <>No products found</>;

  // Set up a title bar for my embedded app
  const breadcrumb = Button.create(appBridge, { label: "My breadcrumb" });
  breadcrumb.subscribe(Button.Action.CLICK, () => {
    appBridge.dispatch(Redirect.toApp({ path: "/breadcrumb-link" }));
  });

  const titleBarOptions = {
    title: "My page title",
    breadcrumbs: breadcrumb,
  };
  TitleBar.create(appBridge, titleBarOptions);

  return (
    <>
      {loading && <span>Loading...</span>}
      {/* A user is viewing this page from a direct link so show them the home page! */}
      {!loading && isRootFrameRequest && <div>Welcome to my cool app's webpage!</div>}
      {!loading &&
        isAuthenticated &&
        data.map((product) => (
          <button
            onClick={(event) => {
              event.preventDefault();
              void deleteProduct({ id: product.id }).then(() => refresh());
            }}
          >
            Delete {product.name}
          </button>
        ))}
    </>
  );
}
```

## 自定义路由器

`@shopify/app-bridge-react` 允许您指定自定义路由器配置,以管理客户端路由。 类似地, Gadget 提供者将允许您指定一个自定义的路由器, 该路由器将转发到 App Bridge .

```tsx
// import Gadget's react hooks for accessing data from your Gadget app
// import the Gadget<->Shopify bindings that manage the auth process with Shopify
import { AppType, Provider as GadgetProvider } from "@gadgetinc/react-shopify-app-bridge";
// import and use Shopify's react components like you might in other Shopify app
import { useMemo } from "react";
// import the instance of the Gadget API client for this app constructed in the other file
import { BrowserRouter, useLocation, useNavigate } from "react-router-dom";
import { api } from "./api";
// import your app's custom routes
import Routes from "./Routes";

function App() {
  const navigate = useNavigate();
  const location = useLocation();
  const history = useMemo(() => ({ replace: (path) => navigate(path, { replace: true }) }), [navigate]);

  const router = useMemo(
    () => ({
      location,
      history,
    }),
    [location, history]
  );

  return (
    // Wrap our main application's react components in the `<GadgetProvider/>` component to interface with Shopify
    // This wrapper sets up the Shopify App Bridge, and will automatically redirect to perform the OAuth authentication if the shopify shop doesn't yet have the store installed.
    <GadgetProvider
      type={AppType.Embedded}
      shopifyApiKey="REPLACE ME with api key from Shopify partners dashboard"
      api={api}
      router={router}
    >
      <Routes />
    </GadgetProvider>
  );
}

export default function AppWrapper() {
  return (
    <BrowserRouter>
      <App />
    </BrowserRouter>
  );
}
```

## 常见问题

### 如何安装 @gadgetinc/react-shopify-app-bridge？

在项目目录运行 npm install @gadgetinc/react-shopify-app-bridge，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：@gadgetinc/core（\>=0\.15\.1）、react（^19\.0\.0）、react-dom（^19\.0\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @gadgetinc/react-shopify-app-bridge 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @gadgetinc/react-shopify-app-bridge 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @gadgetinc/react-shopify-app-bridge 可以商用吗？

@gadgetinc/react-shopify-app-bridge 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @gadgetinc/react-shopify-app-bridge 的下载量有多少？

根据 npm 官方下载统计，@gadgetinc/react-shopify-app-bridge 在 2026/10/16 – 2026/11/14 这 30 天内被下载 17,878 次，日均约 596 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @gadgetinc/react-shopify-app-bridge 还在维护吗？

最新版本 0\.21\.4 发布于 2026/03/31（7 个月前）；至今共发布 73 个版本，其中过去 12 个月发布了 6 个；首次发布于 2022/06/03。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

