TsaiChihWei / learning-blog

1 stars 0 forks source link

[筆記] 模組化與 Library (export & require) #10

Open TsaiChihWei opened 4 years ago

TsaiChihWei commented 4 years ago

require 為 ES5 用法,ES6 用法為 import。

引用別人的模組

var module =require('os')
console.log(module.platform()) //win32

自己寫模組來用

Step 1. 建立一個 JS 檔案 (這邊命名為 myModule.js)

//in myModule.js

function double(x) {
  return x * 2
}

module.exports = {
    double: double,
    triple: function(x){
        return x * 3
    }
}

var myModule = require('./myModule.js') console.log(myModule) => { double: [Function: double], triple: [Function: triple] }

console.log(myModule.double(2)) // output to be 4 console.log(myModule.triple(3)) // output to be 9

+ `var myModule = require('./myModule.js')`:引入的模組非 Node.js 提供或從 NPM 下載安裝,所以要自己輸入檔案路徑。

## 延伸題:另一種輸出指令 (exports.[keyName])
``` js
//in myModule.js
let arr1 = [1, 2, 3]

exports.arr1 = arr1
exports.arr2 = [4, 5, 6]

-------

//in main.js
var myModule = require('./myModule')
console.log(myModule) // output to be => { arr1: [ 1, 2, 3 ], arr2: [ 4, 5, 6 ] } 物件型態
//in myModule.js
let arr1 = [1, 2, 3]
module.exports = arr1

-------

//in main.js
var myModule = require('./myModule')
console.log(myModule) // output to be => [1, 2, 3] 陣列型態