NodeJs的commonjs模块规范(推荐)
nodeJs模块编程,需要将同一模块(文件目录)的js文件中的函数进行向外暴露,具体写法如下
这里我们会用到a.js,b.js以及index.js文件
a.js文件
function test(){
console.log("test-aaa")
}
//该函数没有被暴露出去,所以不会被调用
function init(){
console.log("a.js")
}
module.exports={
//只有被暴露出去的函数才可以在外部被调用
test
}
b.js
function test(){
console.log("test-bbb")
}
module.exports={
//只有被暴露出去的函数才可以在外部被调用
test
}
index.js
//导入a.js文件
const a = require("./a")
//导入b.js文件
const b = require("./b")
a.test() //输出test-aaa
b.test() //输出test-bbb
ES模块化写法(了解)
打开终端,进入项目目录,输入以下命令初始化package.json
npm init
生成后的package.json如下:
{
"name": "file",
"version": "1.0.0",
"description": "",
"main": "test.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "cc",
"license": "ISC"
}
添加 "type":"module",允许使用ES规范
{
"name": "file",
"version": "1.0.0",
"description": "",
"main": "test.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "cc",
"license": "ISC"
}
创建一个test.js文件,在js文件中创建一个模块,模块内有一个函数getName,然后将模块暴露出去
//创建一个模块,将所有函数都放到该模块中
const moduleA={
getName(){
return "logic"
}
}
export default {
moduleA
}
创建index.js文件,用于使用test.js文件暴露出去的函数
import test from "./test.js";
console.log(test.moduleA.getName())
以上就是nodejs模块规范相关的内容,欢迎各位评论教导,如果觉得文章还不错或者有什么地方不懂的,欢迎留言提问点赞🧡🤞🤞🤞🧡