Umi 3中配置Sentry
Sentry官方方法
当在Sentry中新建一个React工程时,它会提示你按照如下的方式,在前端工程中集成Sentry。
首先安装上需要的依赖:
1# Using yarn 2yarn add @sentry/react @sentry/tracing 3 4# Using npm 5npm install --save @sentry/react @sentry/tracing
然后在工程的入口处,添加上Sentry的初始化调用。
1import React from "react"; 2import ReactDOM from "react-dom"; 3import * as Sentry from "@sentry/react"; 4import { Integrations } from "@sentry/tracing"; 5import App from "./App"; 6 7Sentry.init({ 8 dsn: "https://xxxx.ingest.sentry.io/yyyy", // 换成真实的dsn 9 integrations: [new Integrations.BrowserTracing()], 10 11 // We recommend adjusting this value in production, or using tracesSampler 12 // for finer control 13 tracesSampleRate: 1.0, 14}); 15 16ReactDOM.render(<App />, document.getElementById("root")); 17 18// Can also use with React Concurrent Mode 19// ReactDOM.createRoot(document.getElementById('root')).render(<App />);
然而在Umi中,并没有这样一个ReactDOM.render
的位置,它已经被Umi集成在内部了。那应该在哪里添加呢?
umi-plugin-sentry
Github&npm上有一个插件:umi-plugin-sentry,看起来是解决这个问题的。
按照它的文档来看,应该可以在umi的配置文件中,加上
1import { Integrations } from "@sentry/tracing"; 2 3export default { 4 plugins: [ 5 // ... 6 ['umi-plugin-sentry', { 7 dsn: "https://xxxx.ingest.sentry.io/yyyy", // 换成真实的dsn 8 integrations: [new Integrations.BrowserTracing()], 9 tracesSampleRate: 1.0, 10 }], 11 // ... 12 ], 13}
来实现和官方方法相同的效果。
然而Umi3中对plugin的处理有了不兼容的改动,这个插件的这种使用方式,不兼容umi3,在umi3中会报path must be a string
这样的错。因为umi3中要求plugins中的所有值都为字符串,不再兼容数组的形式。
app.tsx
在上面两种方式都失败之后,我找到了另一种方式,即umi的运行时配置。
Umi约定了src/app.tsx
(或src/app.jsx、src/app.js)文件为运行时配置文件,在这个文件中写的代码,会在运行时被加载到。所以我们就可以把它等价为官方文档中需要的 index 文件。
因此修改src/app.tsx
文件,加上官方文档中的代码即可。如果这个文件不存在,直接新建一个即可。
1import * as Sentry from "@sentry/react"; 2import { Integrations } from "@sentry/tracing"; 3 4Sentry.init({ 5 dsn: "https://xxxx.ingest.sentry.io/yyyy", // 换成真实的dsn 6 integrations: [new Integrations.BrowserTracing()], 7 8 // We recommend adjusting this value in production, or using tracesSampler 9 // for finer control 10 tracesSampleRate: 1.0, 11});