1. 程式人生 > 其它 >Node JS 模組化匯入匯出

Node JS 模組化匯入匯出

模組化匯入和匯出 基礎

CommonJS

是Node JS的規範

http://nodejs.cn/api/module.html

程式碼示例

匯出
let a = 1;
function fun () {
  console.log(a);
}

exports.a = a;
exports.fun = fun;
匯入
let example = require('./example');
example.a

這裡的 exports 就是匯出的模組,
然後匯入的 require 就是會把 exports 的物件賦值過來

這個 exports 是對 module.exports 的一個應用, 所以我們也可以使用 module.exports

來進行匯出.

那麼,這兩個的區別是什麼呢?
簡單來說, 就像是在 Node JS 內部, 讓 exports = module.exports 產生了指向.
所以這裡最大的區別就是 直接將 exports = x, 這樣因為這個會直接修改 exports 的指向,
所以匯出就並沒有出現.所以如果要直接只匯出一個物件的化,就需要使用 module.exports 而非 exports 了.

例如:

這種直接賦值, 會因為原來指向的是一個地址, 因為賦值改變了指向,匯出時就沒有了 匯出就是一個 {}
exports = 1;
exports = () => {console.log(1)};
所以就要使用這個方式進行匯出, 避免了地址指向的改變.
module.exports = 1;

本文來自部落格園,作者:tallgy,轉載請註明原文連結:https://www.cnblogs.com/tallgy/p/15389896.html