## 模塊系統
為了讓Node.js的文件可以相互調用,Node.js提供了一個簡單的模塊系統
### 創建模塊
在 Node.js 中,創建一個模塊非常簡單,如下我們創建一個 hello.js 文件,
代碼如下
~~~
exports.world = function() {
console.log('Hello World');
}
~~~
### 引用模塊
代碼如下
~~~
var hello = require('./hello');
hello.world();
~~~
* Node.js 提供了 exports 和 require 兩個對象,其中 exports 是模塊公開的接口,require 用于從外部獲取一個模塊的接口,即所獲取模塊的 exports 對象
其中export 是 module.exports的一個引用
如何創建一個對象模塊
~~~
function Hello() {
var name;
this.setName = function(thyName) {
name = thyName;
};
this.sayHello = function() {
console.log('Hello ' + name);
};
};
module.exports = Hello;
~~~
~~~
//main.js
var Hello = require('./hello');
hello = new Hello();
hello.setName('BYVoid');
hello.sayHello();
~~~
模塊接口的唯一變化是使用 module.exports = Hello 代替了exports.world = function(){}。 在外部引用該模塊時,其接口對象就是要輸出的 Hello 對象本身,而不是原先的 exports。
模塊的加載順序

### 舉例說明模塊查找順序
1.如果a是核心模塊,直接返回核心模塊
2.路徑識別
require('/a')
從根目錄尋找a
require('./a') 相對當前路徑
require('../a') 相對上一級路徑
1.把a當作文件來處理
require('a')
require('a.js')
require('a.json')
require('a.node')
2.把a當目錄來處理
require('a/package.json')
通過尋找該文件里的main字斷的路徑來找到入口
如果main字斷是 enter.js
require('a/enter.js')
require('a/index.js')
require('a/index.json')
require('a/index.node')
3.從node_modules里來尋找模塊
require('a')
require('node_modules/a')
requre('./node_mod')
### 課后習題
1.編寫一個模塊,名為 math.js 模塊有加減乘除是個功能
- Less
- 課程規劃
- Less概述
- 變量
- 混合
- 嵌套
- 繼承
- 導入
- 函數
- 其他
- 實戰
- ES6
- 課程規劃
- ES6概述
- let和const命令
- 變量的解構賦值
- 字符串擴展
- 函數擴展
- 數組擴展
- Set和Map數據結構
- Symbol
- Generator 函數
- Promise對象
- Class語法
- Module 的語法
- ES7和ES8
- 實戰
- VUE
- 課程規劃
- vue概述
- vue實例
- 模版語法
- 計算屬性和偵聽器
- Class和Style的綁定
- 條件渲染
- 列表渲染
- 事件處理
- 表單輸入綁定
- 組件基礎
- 過渡和動畫
- 自定義指令
- 過濾器
- 響應式原理
- 實戰課程
- Node
- 課程規劃
- 課程概述
- node入門實例
- 模塊系統
- 回調函數
- 全局對象
- 常用模塊介紹
- 常用模塊介紹-1
- 常用模塊介紹-2
- 常用模塊介紹-3
- npm使用
- express的使用
- express的使用-1
- webpack基礎
- 實戰
- 微信小程序
- 課程規劃
- 課程概述
- 基本配置和生命周期
- wxml模版
- wxss
- wxs
- 組件
- 微信API
- 自定義組件開發
- 實戰小程序
- Element
- 課程規劃
- 課程概述
- 特性介紹
- 組件介紹-基礎組件
- 組件介紹-表單組件
- 組件介紹-數據展示組件
- 組件介紹-提示組件
- 組件介紹-導航組件
- 組件介紹-其他組件
- 綜合案例