1. 程式人生 > 實用技巧 >module(JS模組系統)

module(JS模組系統)

JS - module(模組系統)

重新學習ES6 倒數第一章 module

什麼是module?

百度的解釋

之前接觸過AngularJS,現在看Dojo,都有對模組的使用。在dojo官網看到這段文字,覺得很好得對JS的模組化的必要性有所解釋,所以記錄下來:

What is a module?

A module is a value that can be accessed by a single reference. If you have multiple pieces of data or functions that you want to expose in a module, they have to be properties on a single object that represents the module. Practically speaking, it's overkill to create a module for a simple value like var tinyModule = 'simple value';

, but it would be valid. Modules start to make a lot more sense for modularizing your code - splitting it up into logical subsets for handling specific functionality. If you want to represent a person with information like name and address, perhaps even add some methods to your person, it starts to make sense to put all that code in a single location. A module is stored in your file system in a single file.

以上意思主要就是:

模組化可被簡單介面引用,當你有很多資料和函式(功能)要作為完整個體展示的時候,你可以把他們作為一個module來定義,這些資料和函式(功能)作為獨立物件去構Module。Module意義就在於模組化程式碼,使你的程式碼分成一個個邏輯上獨立的子集,每個子集處理特定的功能。例如,你想定義人,定義中涉及人的屬性資訊,例如名字、地址。甚至加入一些函式去定義人這個個體。你把定義人的相關程式碼放在同一個地方更為合理。Module就是存放這樣的程式碼的檔案,在整個檔案系統中,這個檔案是可以被單獨呼叫的。

基本瞭解

CommonJS 模組

動態載入 執行到了才會載入

let { stat,exists,readFile } = require('fs')

//等同於

let _fs = require('fs')
let stat = _fs.stat;
let exists = _fs.exists;
let readfile = _fs.readfile;

ES6模組

靜態匯入 頁面載入自動引入

import { stat, exists, readFile } from 'fs'

Module的基本語法

匯出 - Math.js

function add(a,b){
return console.log(a+b);
}
export {add}

匯入- demo.js

import {add} from './Math.js'
add(1,2)
//
import {add as aMath} from './Math.js'
aMath(1,2)

輸出變數寫法

//1.
export var firstName = 'Michael'
export var lastName = 'SwalT'
export var year = '1888'
//2.
var firstName = 'Michael'
var lastName = 'SwalT'
var year = '1888'
export{ firstName, lastName, year }
//3.
function v1(){...}
function v2(){...}
function v3(){...}
export {
v1 as streamV1,
v2 as streamV2,
v3 as streamLatestVersion
}
//執行所載入的模組
import 'loading'

模組的整體載入

//除了指定載入某個輸出值,還可以使用整體載入, 即用星號(*) 指定一個物件, 所有輸出值都載入在這個物件上面
//模組程式碼
export function area(radius){
return Math.PI * radius * radius
}
export function circumference(radius){
return 2 * Math.PI * radius
}

//js
import * as circle from './MathModule.s'
console.log('圓面積:' + circle.area(4))
console.log('圓周長:' + circle.circumference(14))

export default

//module 
export default function(){
console.log('foo')
}
//js
import module from './export-default'
modulr()

注意事項:

import export 不可動態處理 !

import 是隻讀的 本質是輸入介面 所以不允許在載入模組的腳本里面, 改寫介面

但是如果引入的是一個物件, 那麼這個物件的屬性值是允許修改的, 但是很難查錯

等我學完再寫