此篇為記錄 [FE102] 前端必備:JavaScript 課程的筆記。
主要內容為(一)模組化的概念、(二)測試、(三)ES6 部分新語法。
什麼是 Module?為什麼要有 Module?
為了避免不同功能混在一起,互相影響,或是為了讓後續較容易修改會應用在多處的功能。好處是可以改一個地方,其他有用到一樣的功能的地方就會跟著更動。

如何使用 Module?
- 使用
require引入 module:
ref: OS | Node.jsvar os = require('os) console.log(os.platform()) // os 為 node.js 提供的 module,如果是自己寫的前面要加檔案路徑 - 使用
export讓人使用 module:// exportation.js function double (n) { return n * 2 } module.exports = double// importation.js var double = require('./exportation') // 變數名稱可以隨便取 console.log(double(3)) // 6
當輸出不只一種 function 的情形:
第一種作法:
module.exports = {}。// exportation.js function double (n) { return n * 2 } module.exports = { double: double, triple: function(n) { return n * 3 } }// importation.js var importFunction = require('./exportation') console.log(importFunction.triple(2)) // 6 console.log(importFunction.double(2)) // 4- 第二種作法:
exports.<export name>。//exportation.js function double (n) { return n * 2 } exports.double = double exports.triple = function (n) { return n * 3 }// importation.js var importFunction = require('./exportation') console.log(importFunction.triple(2)) // 6 console.log(importFunction.double(2)) // 4
兩者的差異為,當在 importation.js 輸出 newFunction 的話,第二種做法的輸出一定是物件。可以將 exports 視為一個空物件的概念,exports.double 時是在物件裡加上 function。而第一種作法則視賦予 module.exports 什麼型態的值,輸出就是同個型態。例如 module.exports = 'hello',輸出 newFunction 時就會是 string 的型態。
Import, Export ES6 的用法
- 在函式、變數前加上
export:// exportation.js export function double (n) { return n * 2 } export const PI = 3.14 以
import {} from引入module// importation.js import {double, PI} from './exportation' console.log(double(2), PI) // 4 3.14或是可以用以下方式
export,與第 1 點結果一樣://exportation.js function double (n) { return n * 2 } const PI = 3.14 export { double, PI }3-1. 第 3 點
export的用法,乍看之下會以為是物件,但其實不是。所以如果想要用別的名稱export的話,要使用as:// exportation.js export { double as doubleFunction, PI }// importation.js import {doubleFunction, PI} from './exportation'3-2. 如果 import 後覺得命名得也太爛,也可以用
as去更改:// importation import {doubleFunction as d, PI} from './exportation'- 利用
*一次import全部:// importation.js import * as utils from './exportation' console.log(utils.doubleFunction(2)) export default:可以省略{}。// exportation.js export default function double(n) { return n * 2 } export const PI = 3.14// importation.js import double, {PI} from './exportation' // 概念為 {default as double, PI} console.log(double(2), PI) // 4 3.14
註 1:ES6 的 import 與 export 無法用 node 執行,後續會記錄如何以 babel-node 執行。
註 2:default 為 reserved word。


