国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > 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變量(如果已定義)或者當前工作目錄。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 昆山市| 逊克县| 张家界市| 南城县| 龙南县| 宝清县| 铁岭县| 抚远县| 石嘴山市| 永平县| 新宁县| 丹寨县| 内乡县| 沙坪坝区| 贵南县| 湟源县| 鹤庆县| 诏安县| 灯塔市| 东乌珠穆沁旗| 资源县| 姜堰市| 来安县| 沁源县| 墨竹工卡县| 永登县| 周宁县| 尼木县| 桐乡市| 田林县| 彰化市| 南召县| 那坡县| 都江堰市| 阿拉善右旗| 十堰市| 台州市| 成安县| 亚东县| 阜南县| 宁远县|