node require需要注意的缓存问题

require 会优先从cache中读取文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* add.js*/
let value = 0;
module.exports = () => {
console.log(value ++);
};



/* main.js*/
add_1 = require('./add.js');
add = require('./add.js');
add_1(); //1
add_1(); //2
add(); //3

Object.keys(require.cache).forEach(key => console.log(require.cache[key].exports === add););
//true