Node.js入门知识(4)——模块化

50 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第4天,点击查看活动详情

一、模块化概念

在Node中,一个js文件就是一个模块。通过require()函数来引入外部的模块。require()可以传递一个文件的路径作为参数。如果使用相对路径,必须使用./或../。

二、require()的用法

1)在03module.js中引入02module.js

02module.js
console.log("我是一个单独的模块,02module.js");
03module.js
require("./02module.js");
运行: image.png

2)在03module.js中使用02module.js中的变量

02module.js
console.log("我是一个单独的模块,02module.js");
var x = 10;
var y = 20;
03module.js
require("./02module.js");
var z = x+y;
console.log(z);
运行: image.png
原因:使用require()引入模块以后,该函数会返回一个对象,这个对象表示的是引入的模块;在node中,每一个js文件中的js代码都是独立运行在一个函数里而不是全局作用域,所以一个模块中的函数和变量在其他模块中无法访问。
通过exports导出模块的变量和方法,将需要暴露的变量或方法设置为exports的属性即可。

将以上代码修改为:
方法1:
02module.js
image.png 03module.js
image.png
补充:require(“./02module.js”)也可以省略.扩展名require(“./02module”)

三、综合运用

定义一个math模块,在该模块中提供两个方法
add(a,b)求两数的和
mul(a,b)求两数的积
math.js
image.png image.png