Expo

了解如何在 Expo 管理的项目中设置 Sentry React Native SDK。

要在你的 Expo 项目中设置 Sentry React Native SDK,请按照本页面的步骤操作。

使用 Sentry Wizard 自动修补你的项目,如下所示。或者,如果你愿意,也可以按照 手动安装。你只需要修补项目一次,然后可以将修补后的文件添加到你的版本控制系统中。

Copied
npx @sentry/wizard@latest -i reactNative
Sentry Wizard 将执行以下任务
  • 安装 @sentry/react-native 包。
  • @sentry/react-native/metro 添加到 metro.config.js Metro 配置中。
  • @sentry/react-native/expo 添加到 app.json Expo 配置中。
  • 为 Android 启用 Sentry React Native Gradle 构建步骤以自动上传生成的源映射和调试符号。
  • 包裹 Bundle React Native code and images Xcode 项目构建阶段脚本,以上传生成的源映射并收集打包的 node 模块。
  • 添加 Upload Debug Symbols to Sentry Xcode 项目构建阶段。
  • 运行 pod install
  • ios/sentry.propertiesandroid/sentry.propertiesenv.local 中存储构建凭据。
  • 在你的 layout.tsx 文件中配置 Sentry 以使用提供的 DSN。

如果你不使用 Wizard,请安装 @sentry/react-native 包:

Copied
npx expo install @sentry/react-native

导入 @sentry/react-native 包并使用你的 DSN 调用 init

Copied
import { Text, View } from "react-native";
import * as Sentry from "@sentry/react-native";

Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",

  // Set tracesSampleRate to 1.0 to capture 100%
  // of transactions for tracing.
  // We recommend adjusting this value in production
  // Learn more at
  // https://docs.sentry.io/platforms/javascript/configuration/options/#traces-sample-rate
  tracesSampleRate: 1.0,
});

function App() {
  return (
    <View>
      <Text>Expo Example!</Text>
    </View>
  );
}

export default Sentry.wrap(App);

使用 Sentry.wrap 包裹应用程序的根组件:

Copied
export default Sentry.wrap(App);

为了确保在原生应用构建期间自动上传 bundles 和源映射,将 withSentry 添加到 Expo 应用程序配置中:

Copied
{
  "expo": {
    "plugins": [
      [
        "@sentry/react-native/expo",
        {
          "url": "https://sentry.io/",
          "note": "Use SENTRY_AUTH_TOKEN env to authenticate with Sentry.",
          "project": "example-project",
          "organization": "example-org"
        }
      ]
    ]
  }
}

将身份验证令牌添加到你的环境:

Copied
# DO NOT COMMIT YOUR AUTH TOKEN
export SENTRY_AUTH_TOKEN=sntrys_YOUR_TOKEN_HERE

为了确保生成的 bundles 和源映射分配唯一的 Debug ID,将 Sentry Serializer 添加到 Metro 配置中:

Copied
// const { getDefaultConfig } = require("expo/metro-config");
const { getSentryExpoConfig } = require("@sentry/react-native/metro");

// const config = getDefaultConfig(__dirname);
const config = getSentryExpoConfig(__dirname);

module.exports = config;

SDK 需要访问有关设备和应用程序的某些信息以实现其基本功能。其中一些 API 被认为与隐私相关。将隐私清单添加到你的 Xcode 项目中,以确保你的应用程序符合 Apple 的指南。阅读 Apple 隐私清单 指南,了解更多关于如何添加 Sentry SDK 所需记录的信息。

为了验证一切是否按预期工作,构建应用程序的 Release 版本,并通过添加以下代码发送一个测试事件到 Sentry:

Copied
<Button
  title="Try!"
  onPress={() => {
    Sentry.captureException(new Error("First error"));
  }}
/>;

  • 不要提交你的授权令牌。相反,使用环境变量如 SENTRY_AUTH_TOKEN
  • 应用程序的 Release 版本的源映射会在原生应用构建期间自动上传。
  • 在开发过程中,源代码通过 Metro Server 解析,不会使用源映射。这目前在 Web 上不起作用。