Nodejs中的require函数的具体使用方法

2020-06-17 06:53:04易采站长站整理

说明

本文参考Node官网文档版本为v11.12.0。

本文主要分析了Nodejs中require导入JSON和js文件时得到的结果,同时简单涉及到了Nodejs中模块导出module.exports和exports的用法。

引言

在阅读webpack源码的过程当中,见到如下一行代码:


const version = require("../package.json").version

故引申出对Nodejs中require的学习。

require介绍

在Node.js的文档中,require的相关文档是在Modules目录下,属于Nodejs模块化系统的一部分。

require是一个函数。通过typeof或者Object.prototype.toString.call()可以验证这个结论:


console.log(require) // 输出:Function
console.log(Object.prototype.toString.call(require) // 输出:[object Function]

通过直接打印require,可以发现在require函数下还挂载着若干个静态属性,这些静态属性也可以在Nodejs的官方文档中直接找到相关的说明:


{ [Function: require] resolve: { [Function: resolve] paths: [Function: paths] },
main:
Module {
id: '.',
exports: {},
parent: null,
filename: '/Users/bjhl/Documents/webpackSource/index.js',
loaded: false,
children: [],
paths:
[ '/Users/bjhl/Documents/webpackSource/node_modules',
'/Users/bjhl/Documents/node_modules',
'/Users/bjhl/node_modules',
'/Users/node_modules',
'/node_modules' ] },
extensions:
[Object: null prototype] { '.js': [Function], '.json': [Function], '.node': [Function] },
cache:
[Object: null prototype] {
'/Users/bjhl/Documents/webpackSource/index.js':
Module {
id: '.',
exports: {},
parent: null,
filename: '/Users/bjhl/Documents/webpackSource/index.js',
loaded: false,
children: [],
paths: [Array] } } }

require函数静态属性

这里之后再详细补充。

require使用

在官网文档中可以看到如下关于require的说明:

require(id)#  Added in: v0.1.13  id module name or path  Returns: exported module content  Used to import modules, JSON, and local files. Modules can be imported from node_modules. Local modules and JSON files can be imported using a relative path (e.g. ./, ./foo, ./bar/baz, ../foo) that will be resolved against the directory named by __dirname (if defined) or the current working directory.

同时还给出了三种require的使用方法:


// Importing a local module:
const myLocalModule = require('./path/myLocalModule');

// Importing a JSON file:
const jsonData = require('./path/filename.json');