CommonJs

巧了我就是萌 提交于 2020-02-09 22:02:16
特点
  • 每个文件被视为一个独立的模块
关键字

exports , module , require

exports

exports 变量是在模块的文件级别作用域内有效的,它在模块被执行前被赋予 module.exports 的值。

它有一个快捷方式,以便 module.exports.f = … 可以被更简洁地写成 exports.f = …
注意,就像任何变量,如果一个新的值被赋值给 exports,它就不再绑定到 module.exports:

12
module.exports.hello = true; exports = { hello: false };  // 不导出,只在模块内有效
Node导出模块常用方式
到处命名空间
12345
const fs = require('fs');fs.unlink('/tmp/hello', (err) => {  if (err) throw err;  console.log('成功删除 /tmp/hello');});
导出函数
123456 大专栏  CommonJs7
//express.jsmodule.exports = function(){    //some code here};//app.jsconst express = require('./express');const app = express();
导出高阶函数
123456789101112
//serve-favicon.jsmodule.exports = function(path){    //some code here    return function(req,res,next){        //some code here    }}const path = require('path');const express = require('express');const favicon = require('./serve-favicon');const app = express();app.use(favicon(path.join(__dirname, '/public/favicon.ico')));
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!