详解 RN 中的 require()

点我查看英文原文。

在 index.android.js 中会看到 var React = require('react-native'),require() 函数是干啥用的?本文解答了这个问题。解释一下下面两行代码:

var React = require('react-native');

var {
  AppRegistry,
  Image,
  ListView,
  StyleSheet,
  Text,
  View,
} = React;

React 对象是个集合,AppRegistry、Image、ListView 等这些组件是这个集合的元素。这两行代码就是把要用到的这些元素 import 进来了。

Node.js 采用了 CommonJS 的模块系统,require() 是 Node.js 的内置函数,是引入其他文件中的 js 模块的最简单的方法。该函数最基本的功能是,读取 js 文件,执行文件,然后返回 exports 对象。

举例说明。example.js 文件内容如下:

console.log("evaluating example.js");

var invisible = function () {
  console.log("invisible");
}

exports.message = "hi";

exports.say = function () {
  console.log(message);
}

所以,如果你执行代码

var example = require('./example.js')

那么,example.js 文件会被执行,对象 example 等于:

{ message: "hi", say: [Function] }

如果你改变 exports 对象,必须使用 module.exports,例如文件 example2.js 的内容如下:

module.exports = function () {
  console.log("hello world")
}

require('./example2.js')() //require itself and run the exports object

js 文件一旦被 require,exports 对象就被会缓存。如下代码可以证明这一点:

node> require('./example.js')
evaluating example.js
{ message: 'hi', say: [Function] }
node> require('./example.js')
{ message: 'hi', say: [Function] }
node> require('./example.js').message = "hey" //set the message to "hey"
'hey'
node> require('./example.js') //One might think that this "reloads" the file...
{ message: 'hey', say: [Function] } //...but the message is still "hey" because of the module cache.

可以看出,example.js 第一次被执行后,后面再调用 require() 方法只是调用缓存数据,而不是重新读取文件并执行。显然,这是有副作用的。

require() 方法寻找文件的规则有点复杂,基本规律是:如果文件路径不是以 “./” 或 “/” 开头,那么这个文件要么是被当做 Node.js 的核心模块,要么是本地 node_modules 文件夹中的一个依赖。如果是文件路径以 “./” 开头,则被当做是相对路径;如果以 “/” 开头,则被认为是绝对路径。注意:文件路径中的文件名可以省略 “.js” 后缀,require() 函数会在需要的时候自动加上。

还有一点要注意:if the filename passed to require is actually a directory, it will first look for package.json in the directory and load the file referenced in the main property. Otherwise, it will look for an index.js.

你可能感兴趣的:(react,node.js,require)