模块是一门语言编写大项目的基石, 因此, 了解如何组织, 编写, 编译, 加载模块很重要. 这里主要谈谈 Node 中的模块加载.
1.Node 中的模块, 主要使用 require 来加载模块
require("./") --- 加载本文件夹下面的 package.JSON, 如果没有, 则加载 index.JS,index.node
require("some.js") -- 加载本文件夹下面的 some.JS 文件
require("lib/some.js") -- 加载 lib/some.JS 文件
require("modulename") -- 加载当前目录 node_modules/modulename 文件夹内的 package.JSON, 如果没有, 则加载 index.JS,index.node. 如果当前目录找不到以上内容, 则进入指定全局模块缓存目录中加载 modulename 文件夹中的内容, 如还未找到, 则进入系统环境变量 NODE_PATH 指定的路径中加载 modulename 文件夹内的内容. 涉及到的目录, 请参看 NPM 路径设置.
2.Node 中创建 / 导出模块: module.exports
Module.exports 才是真正的接口, exports 只不过是它的一个辅助工具. 最终返回给调用的是 Module.exports 而不是 exports.
所有的 exports 收集到的属性和方法, 都赋值给了 Module.exports.
当然, 这有个前提, 就是 Module.exports 本身不具备任何属性和方法. 如果, Module.exports 已经具备一些属性和方法, 那么 exports 收集来的信息将被忽略.
修改 rocker.JS 如下:
- module.exports = 'ROCK IT!';
- exports.name = function() {
- console.log('My name is Lemmy Kilmister');
- };
- // 再次引用执行 rocker.JS :
- var rocker = require('./rocker.js');
- rocker.name(); // TypeError: Object ROCK IT! has no method 'name'
发现报错: 对象 "ROCK IT!" 没有 name 方法, rocker 模块忽略了 exports 收集的 name 方法, 返回了一个字符串 "ROCK IT!".
结论:
1. 模块并不一定非得返回 "实例化对象". 你的模块可以是任何合法的 JavaScript 对象 --boolean, number, date, JSON, string, function, array 等等.
2. 模块可以是任何你设置给它的东西. 如果你没有显式的给 Module.exports 设置任何属性和方法, 那么你的模块就是 exports 设置给 Module.exports 的属性.
实例:
- module.exports = function(name, age) {
- this.name = name;
- this.age = age;
- this.about = function() {
- console.log(this.name +'is'+ this.age +'years old');
- };// 欢迎加入全栈开发交流圈一起学习交流: 864305860
- // 面向 1-3 年前端人员
- // 帮助突破技术瓶颈, 提升思维能力
- };
调用:
- ar Rocker = require('./rocker.js');
- var r = new Rocker('Ozzy', 62);
- r.about(); // Ozzy is 62 years old
3. 如果你的模块是一个特定的类型, 就用 Module.exports;
如果你模块是一个典型的 "实例化对象" 就用 exports.
给 Module.exports 添加属性类似于给 exports 添加属性. 例如:
- module.exports.name = function() {
- console.log('My name is Lemmy Kilmister');
- };
同样, exports 是这样的
- exports.name = function() {
- console.log('My name is Lemmy Kilmister');
- };
请注意, 这两种结果并不想同. 前面已经提到 module.exports 是真正的接口, exports 只不过是它的辅助工具. 推荐使用 exports 导出 (实例化对象), 除非你打算从原来的 "实例化对象" 改变成一个类型.
注意, webpack 默认是支持 es6 的. 所以, 在 导入 / 导出模块 的时候, 也可以用 es6 的写法.
小结: 1.Node.JS 中的用 require,exports 处理模块
2.. 注意区别 Node.JS 与 es6 中模块导入, 导出方法的不同之处
结语
感谢您的观看, 如有不足之处, 欢迎批评指正.
来源: http://www.qdfuns.com/article/51117/f0db55c090865130f609fc7aab8bab2e.html