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