0%

nodejs使用模块

nodejs使用模块

创建和加载模块

nodejs提供了exports和require来对模块进行操作,exports是模块公开的接口,require用于获取模块的exports对象

创建一个module.js文件,并公开一个方法

1
2
3
exports.sayHello = function(name){
console.log('Hello '+name);
}

在同目录下创建usemodule.js文件,调用上述方法

1
2
3
// 加载module模块
var myModule = require('./module');
myModule.sayHello('老张');

执行结果

1
2
zhanghedeMacBook:module zhanghe$ node usemodule.js 
Hello 老张

在开发nodejs程序的时候需要使用很多模块,总不能一个一个的安装吧?那当然不会这么干,npm允许使用package.json文件来指定应用程序中要用的模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
{
"name": "exam", // 包的名称
"version": "1.0.0",//版本
"private": true,
"scripts": {
"serve": "vue-cli-service serve --mode dev",
"build": "vue-cli-service build --mode prod",
"build:dev": "vue-cli-service build --mode dev",
"build:test": "vue-cli-service build --mode test",
"build:pre": "vue-cli-service build --mode pre",
"build:prod": "vue-cli-service build --mode prod",
"lint": "vue-cli-service lint"
},
"dependencies": { // 包的依赖
"axios": "^0.19.0",
"core-js": "^3.10.0",
"element-ui": "^2.15.0",
"js-cookie": "2.2.0",
"normalize.css": "8.0.1",
"nprogress": "0.2.0",
"vue": "^2.6.10",
"vue-router": "^3.5.1",
"vuex": "^3.6.2"
},
"devDependencies": {
"@vue/cli-plugin-babel": "^4.5.12",
"@vue/cli-plugin-eslint": "^4.5.12",
"@vue/cli-plugin-router": "^4.5.12",
"@vue/cli-plugin-vuex": "^4.5.12",
"@vue/cli-service": "^4.5.12",
"@vue/eslint-config-standard": "^4.0.0",
"babel-eslint": "^10.0.3",
"eslint": "^5.16.0",
"eslint-plugin-vue": "^5.0.0",
"node-sass": "^4.14.1",
"sass-loader": "^8.0.0",
"svg-sprite-loader": "4.1.6",
"vue-template-compiler": "^2.6.10"
}
}

欢迎关注我的其它发布渠道