[TOC] Come on 开始新的征程!
模块:在计算机程序的开发过程中,随着程序代码越写越多,在一个文件里代码就会越来越长,越来越不容易维护。
为了编写可维护的代码,我们把很多函数分组,分别放到不同的文件里,这样每个文件包含的代码就相对较少,很多编程语言都采用这种组织代码的方式。 在Node环境中,一个.js文件就称之为一个模块(module)。
模块/包与CommonJS示例图:
WeiyiGeek.模块包CommonJS
Q:使用模块有什么好处?
Tips:相同名字的函数和变量完全可以分别存在不同的模块中,因此我们自己在编写模块时,不必考虑名字会与其他模块冲突。
Nodejs模块基于CommonJ规范分类:
案例(1):
//采用ES6规范 //######(1)内置模块########## const os = require('os') //nodejs API console.log(os.hostname) //DESKTOP-OVF3TEN //#########(2)第三方模块 利用npm或者cnpm下载安装模块包 ############ > npm init #在项目中创建配置文件 > npm install request --save #会建立 node_modules 文件夹存放模块包,配置里面也将写入dependencies; //第三方模块使用 const request = require('request') request({ url:'https://api.douban.com/v2/movie/top250', json: true },(error,Response,body)=>{ console.log(JSON.stringify(body, null, 2)) //空白替换 / 2 表示缩进 }) //##############(3) 自定义模块 ############### //建立一个src文件夹存储自定义模块 ./src/greeting.js //第一步建立模块 'use strict'; const hello = () =>{ console.log('Hello ~') } //第二步暴露模块 模块名称 = 处理方法 ////module.exports = hello; 下面可直接调用hello() = > Demo() module.exports.hello = hello //#主调用文件moduel.js //在使用require()引入模块的时候,请注意模块的相对路径,因为main.js和hello.js位于同一个目录,所以我们用了当前目录.: const Demo = require('./src/greeting.js') Demo.hello() //Hello ~
案例2:自定义模块
//########## src\hello.js ########### //hello.js文件就是一个模块,模块的名字就是文件名 'use strict'; var s = 'Hello'; function greet(name) { console.log(s + ', ' + name + '!'); } module.exports = greet; //直接暴露方法名 (注意这点) //########## module_1.js ########### 'use strict'; // 引入hello模块: var greet = require('./src/hello'); var s = 'WeiyiGeek'; //成功地引用了hello.js模块中定义的greet()函数 greet(s); // Hello, WeiyiGeek! (注意)
注意:
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句