說明
本文參考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');從以上文檔中可以得出以下信息:
新聞熱點
疑難解答
圖片精選