首页 > 语言 > JavaScript > 正文

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

2024-05-06 15:41:13
字体:
来源:转载
供稿:网友

说明

本文参考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) // 输出:Functionconsole.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');// Importing a module from node_modules or Node.js built-in module:const crypto = require('crypto');

从以上文档中可以得出以下信息:

    require接受一个参数,形参名为id,类型是String。 require函数return的是模块到处的内容,类型是任意。 require函数可以导入模块、JSON文件、本地文件。模块可以通过一个相对路径从node_modules、本地模块、JSON文件中导出,该路径将针对__dirname变量(如果已定义)或者当前工作目录。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选