├── .gitignore
├── README.md
├── config
├── env.js
├── jest
│ ├── cssTransform.js
│ └── fileTransform.js
├── paths.js
├── polyfills.js
├── webpack.config.dev.js
├── webpack.config.prod.js
└── webpackDevServer.config.js
├── package-lock.json
├── package.json
├── public
├── favicon.ico
├── index.html
└── manifest.json
├── scripts
├── build.js
├── post-sym.js
├── start.js
├── test.js
└── transform-release.js
├── sentry.properties
├── src
├── App.css
├── App.js
├── App.test.js
├── SentryBoundary.js
├── index.css
├── index.js
├── logo.svg
└── registerServiceWorker.js
└── yarn.lock
/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/ignore-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 |
6 | # testing
7 | /coverage
8 |
9 | # production
10 | /build
11 |
12 | # misc
13 | .DS_Store
14 | .env.local
15 | .env.development.local
16 | .env.test.local
17 | .env.production.local
18 |
19 | npm-debug.log*
20 | yarn-debug.log*
21 | yarn-error.log*
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # React-Sentry-Demo
2 |
3 | > 在React上集成Sentry的demo
4 |
5 | ## 文件说明:
6 |
7 | ### `scripts/transform-release.js`
8 |
9 | 因为上传`source-map`到`Sentry`,需要`release`字段信息才可以。这个字段可以把它理解成`package.json`里的`version`字段。意思差不多
10 |
11 | 这个文件就是把`package.json`里的`release`字段保存成json文件,文件在`src`目录下。
12 |
13 | src目录下有代码需要`release`字段,但是因为限制,而不能使用`import`或者`require`去引入不在src目录下的文件。所以需要把文件放在src目录下,方便去调用。打包时会把这个文件的内容打包到最终的js文件里。其实src下的代码是可以去引入根目录的package.json的文件的,但是这样一来会把整个package.json打包到最终js文件里。这样会导致项目上线时,对外暴露了整个package.json的内容。所以写了需要这个文件把package.json里的`release`字段保存成一个json文件,相当于一个中间件的作用。避免之前所说的问题。同时也减少了最终打包的大小。
14 |
15 | 这个文件会被`package.json`里的`scripts`里的`build:sentry`去调用。调用命令为: `npm run build:sentry`
16 |
17 | 生成的json文件分别被`scripts/post-sym.js`和`src/index.js`文件去引用。
18 |
19 | ### `scripts/post-sym.js`
20 |
21 | 此文件用于上传source-map文件到sentry服务器上。
22 |
23 | 上传之后,会把source-map文件删除,防止在项目上线后,source-map文件泄露。
24 |
25 | 这个文件会对当前的环境进行检查,看是否有什么意外情况导致无法上传。
26 |
27 | ### `sentry.properties`
28 |
29 | 此文件为`sentry`的配置文件,用于上传的验证和最终上传到`sentry`的哪个项目下。
30 |
31 | ```ini
32 | defaults.url # 为sentry的服务器,如果不写,默认就是https://sentry.io/。如果公司内网有搭建此项目,这里把地址更换下就好。
33 | defaults.org # 如果项目属于某一个team下,那就填写此team的名称
34 | defaults.project # 项目的名称
35 | auth.token # 验证的token,需要保证此token具有以下权限: project:read、project:write、project:releases
36 | ```
37 |
38 | ### `src/SentryBoundary.js`
39 |
40 | 此组件用于捕获错误,并把错误发送到sentry服务器。这个和之前的`scripts/post-sym.js`做的两件事情,不要搞混。
41 |
42 | 此组件,是把捕获到的错误,发送到sentry服务器,但是发送到服务器的时候,js已经被混淆加密过了。所以需要`scripts/post-sym.js`文件去上传source-map,这样在`sentry`看的时候,就能准确的定位到错误的位置。下面是不上传source-map文件和上传`source-map`后的截图对比:
43 |
44 | 
45 |
46 | 
47 |
48 | 此组件需要放在`React`的组件最外面,代码如下:
49 |
50 | ```javascript
51 | ReactDOM.render(
52 |
,
57 | document.getElementById("root")
58 | );
59 | ```
60 |
61 | ## 流程说明:
62 |
63 | ### 编写sentry.properties
64 |
65 | 首先你去sentry申请一个[API keys](https://sentry.io/settings/account/api/auth-tokens/)。保证其具有以下权限: project:read、project:write、project:releases。
66 |
67 | 打开你的项目,记录下url地址。如: `https://sentry.io/black-hole-m9/react/`,这里的`black-hole-9`就是org,`react`就是project。
68 |
69 | 根据以上信息,我们编写`sentry.properties`文件内容如下:
70 |
71 | ```ini
72 | defaults.url=https://sentry.io/
73 | defaults.org=black-hole-m9
74 | defaults.project=react
75 | auth.token=ac1c75ca4f6b4c77a47c9b15dee8dfab86fce6fc4f484363a63e9d29f0bf6572
76 | ```
77 |
78 | ### 获取release
79 |
80 | 前文也说道,sentry上传source-map需要`release`字段信息。现在我们可以确定的是这个信息,会被两处地方调用。
81 |
82 | 一次是上传的时候,告知sentry当前的`release`。一次是应用初始化捕获错误的时候,告知错误发到哪个`release`。这样一来,错误和source-map就可以对应上了。
83 |
84 | 所以根据上面的需求,编写了`scripts/transform-release.js`。同时在package.json里的scripts对象上增加了一条: `"transform-release": "node scripts/transform-release.js"`
85 |
86 | *如果不是要上传source-map,而是上传PDB、SYM、dSYM等Symbols link(Debug Information Files),那不需要source-map,其上传命令也是不一样。*
87 |
88 | ### 编写组件
89 |
90 | 因为我们要捕获错误,在纯JavaScript里(不含框架)的Web应用中,sentry的做法是重写`window.onerror`来达到捕获错误的功能,但是在`React`中,却不一样。需要增加一个组件,其组件在最外层。
91 |
92 | 组件的代码其实很简单,通过`componentDidCatch`来监听所有子组件的catch。然后可以通过返回一个`render`,来替换掉崩溃的组件。具体的例子可以见: [Example](https://wiggly-power.glitch.me/),[Example源码](https://glitch.com/edit/#!/wiggly-power)
93 |
94 | ### 重写window.error
95 |
96 | 这里的重写并不是指我们来重新,sentry已经帮我们做好了,我们只需要去调用他的方法就好了。
97 |
98 | 我们打开应用的入口文件,也就是`src/index.js`,在里面通过`import Raven from "raven-js"`去引入`sentry`的包,再使用:`Raven.config(/** 配置 **/).install()`就好了
99 |
100 | 如果你没有跳过上面的部分,那你应该知道,这里就要需要`release`字段了。在`config`里,增加一个`release`字段,通过引入我们之前生成的json文件去获取
101 |
102 | ### 上传source-map
103 |
104 | 这里一定要开启生成source-map的选项。不然会报错的。上传的的命令其实就是下面这样:
105 |
106 | ```sh
107 | sentry-cli releases new {releases字段值}
108 | sentry-cli releases files {releases字段值} upload-sourcemaps {js文件和js.map所在目录。如果没有找到,sentry会遍历其子目录} --url-prefix '~/{过滤规则}'`;
109 | ```
110 |
111 | 这里需要注意的地方是`--url-prefix`这个字段,你可以把它想象成nginx的location。
112 |
113 | 这里假设过滤规则如下: `~/static/js/` 当打开网站访问时,请求js的url地址为:`xxx.com/static/js/js文件名.js`时,就会匹配成功,当是`xxx.com/aa/js/js文件名.js`时,将不会匹配。
114 |
115 | 我把这个些操作写成一个js脚本,让其自动化。其中包含环境检测、认证检测、上传source-map、删除本地source-map。
116 |
117 | 这个脚本就是`srcipts/post-sym.js`,同时在package.json里的scripts对象上增加了一条:
118 | `"post-sym": "cross-env NODE_ENV=production SENTRY_PROPERTIES=./sentry.properties node scripts/post-sym.js"`
119 |
120 | `NODE_ENV`这个需要是因为其文件里调用了webpack配置,如果不调用则会报错,`SENTRY_PROPERTIES`则是告知我们的sentry配置。
121 |
122 | ### 终章
123 |
124 | 现在我们把上面的`npm script`统一一下,成为新的`npm script`:
125 | `"build:sentry": "npm run transform-release && npm run build && npm run post-sym"`
126 |
127 | 这样,以后我们写完代码,就可以通过`npm run build:sentry`来自动化了。后续的版本迭代,只需要修改`package.json`里的`releases`就好。
--------------------------------------------------------------------------------
/config/env.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const fs = require('fs');
4 | const path = require('path');
5 | const paths = require('./paths');
6 |
7 | // Make sure that including paths.js after env.js will read .env variables.
8 | delete require.cache[require.resolve('./paths')];
9 |
10 | const NODE_ENV = process.env.NODE_ENV;
11 | if (!NODE_ENV) {
12 | throw new Error(
13 | 'The NODE_ENV environment variable is required but was not specified.'
14 | );
15 | }
16 |
17 | // https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
18 | var dotenvFiles = [
19 | `${paths.dotenv}.${NODE_ENV}.local`,
20 | `${paths.dotenv}.${NODE_ENV}`,
21 | // Don't include `.env.local` for `test` environment
22 | // since normally you expect tests to produce the same
23 | // results for everyone
24 | NODE_ENV !== 'test' && `${paths.dotenv}.local`,
25 | paths.dotenv,
26 | ].filter(Boolean);
27 |
28 | // Load environment variables from .env* files. Suppress warnings using silent
29 | // if this file is missing. dotenv will never modify any environment variables
30 | // that have already been set. Variable expansion is supported in .env files.
31 | // https://github.com/motdotla/dotenv
32 | // https://github.com/motdotla/dotenv-expand
33 | dotenvFiles.forEach(dotenvFile => {
34 | if (fs.existsSync(dotenvFile)) {
35 | require('dotenv-expand')(
36 | require('dotenv').config({
37 | path: dotenvFile,
38 | })
39 | );
40 | }
41 | });
42 |
43 | // We support resolving modules according to `NODE_PATH`.
44 | // This lets you use absolute paths in imports inside large monorepos:
45 | // https://github.com/facebookincubator/create-react-app/issues/253.
46 | // It works similar to `NODE_PATH` in Node itself:
47 | // https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
48 | // Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored.
49 | // Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims.
50 | // https://github.com/facebookincubator/create-react-app/issues/1023#issuecomment-265344421
51 | // We also resolve them to make sure all tools using them work consistently.
52 | const appDirectory = fs.realpathSync(process.cwd());
53 | process.env.NODE_PATH = (process.env.NODE_PATH || '')
54 | .split(path.delimiter)
55 | .filter(folder => folder && !path.isAbsolute(folder))
56 | .map(folder => path.resolve(appDirectory, folder))
57 | .join(path.delimiter);
58 |
59 | // Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be
60 | // injected into the application via DefinePlugin in Webpack configuration.
61 | const REACT_APP = /^REACT_APP_/i;
62 |
63 | function getClientEnvironment(publicUrl) {
64 | const raw = Object.keys(process.env)
65 | .filter(key => REACT_APP.test(key))
66 | .reduce(
67 | (env, key) => {
68 | env[key] = process.env[key];
69 | return env;
70 | },
71 | {
72 | // Useful for determining whether we’re running in production mode.
73 | // Most importantly, it switches React into the correct mode.
74 | NODE_ENV: process.env.NODE_ENV || 'development',
75 | // Useful for resolving the correct path to static assets in `public`.
76 | // For example,
.
77 | // This should only be used as an escape hatch. Normally you would put
78 | // images into the `src` and `import` them in code to get their paths.
79 | PUBLIC_URL: publicUrl,
80 | }
81 | );
82 | // Stringify all values so we can feed into Webpack DefinePlugin
83 | const stringified = {
84 | 'process.env': Object.keys(raw).reduce((env, key) => {
85 | env[key] = JSON.stringify(raw[key]);
86 | return env;
87 | }, {}),
88 | };
89 |
90 | return { raw, stringified };
91 | }
92 |
93 | module.exports = getClientEnvironment;
94 |
--------------------------------------------------------------------------------
/config/jest/cssTransform.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | // This is a custom Jest transformer turning style imports into empty objects.
4 | // http://facebook.github.io/jest/docs/en/webpack.html
5 |
6 | module.exports = {
7 | process() {
8 | return 'module.exports = {};';
9 | },
10 | getCacheKey() {
11 | // The output is always the same.
12 | return 'cssTransform';
13 | },
14 | };
15 |
--------------------------------------------------------------------------------
/config/jest/fileTransform.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const path = require('path');
4 |
5 | // This is a custom Jest transformer turning file imports into filenames.
6 | // http://facebook.github.io/jest/docs/en/webpack.html
7 |
8 | module.exports = {
9 | process(src, filename) {
10 | return `module.exports = ${JSON.stringify(path.basename(filename))};`;
11 | },
12 | };
13 |
--------------------------------------------------------------------------------
/config/paths.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | const path = require('path');
4 | const fs = require('fs');
5 | const url = require('url');
6 |
7 | // Make sure any symlinks in the project folder are resolved:
8 | // https://github.com/facebookincubator/create-react-app/issues/637
9 | const appDirectory = fs.realpathSync(process.cwd());
10 | const resolveApp = relativePath => path.resolve(appDirectory, relativePath);
11 |
12 | const envPublicUrl = process.env.PUBLIC_URL;
13 |
14 | function ensureSlash(path, needsSlash) {
15 | const hasSlash = path.endsWith('/');
16 | if (hasSlash && !needsSlash) {
17 | return path.substr(path, path.length - 1);
18 | } else if (!hasSlash && needsSlash) {
19 | return `${path}/`;
20 | } else {
21 | return path;
22 | }
23 | }
24 |
25 | const getPublicUrl = appPackageJson =>
26 | envPublicUrl || require(appPackageJson).homepage;
27 |
28 | // We use `PUBLIC_URL` environment variable or "homepage" field to infer
29 | // "public path" at which the app is served.
30 | // Webpack needs to know it to put the right