invariant
这是一个npm的包
npm package地址:https://www.npmjs.com/package/invariant
invariant(condition, message)
condition:true或false,一个表达式,也可以是空字符串表示false,非空的字符串表示true
message:显示的消息
1 | var invariant = require('invariant'); |
主要的作用类似一个照妖镜,对程序进行断言,在开发模式下将错误显示在浏览器上,生产模式下显示在console里。
示例
使用`create-react-app’命令创建一个项目,名字随意起
引入
invariant
包,运行命令npm install invariant --save
更改文件代码
src/index
,如下1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
+ import invariant from 'invariant';
+ let root = document.getElementById('root')
+ invariant(root, `Can't find root HTMLElement`);
+ ReactDOM.render(<App />, root);
- ReactDOM.render(<App />, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
serviceWorker.unregister();安装上述更改代码后,程序可正常运行,目的是为了给
root
这个节点添加一个断言,当没有这个节点时,程序会报错提示更改文件代码
src/index
,如下,让其出现错误1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import invariant from 'invariant';
- let root = document.getElementById('root')
let root = document.getElementById('root2')
invariant(root, `Can't find root HTMLElement`);
ReactDOM.render(<App />, root);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
serviceWorker.unregister();修改以上代码目的,对
root
进行断言,我们更改root
的名字为root2
,实际并没有这个节点,这时候运行程序在开发环境下,网页会显示出我们自定义的错误,同时console中也会显示,当为生产环境的时候,只在conso中显示,实际效果如下图: