使用 SystemJS 載入 moment.js
SystemJS 允許編寫和使用依賴於 ECMAScript 6 匯入和匯出語句的模組化 javacsript 程式碼。一個很好的例子是 moment.js 庫,它自從 2.10.0 釋出的 moment.js 開始在 npm 上釋出 ECMAScript 6 原始碼。
安裝先決條件
npm install moment
npm install systemjs
npm install traceur
注意:SystemJS 需要一個轉換器來將 ECMAScript 6 javacsript 編譯成可以在當前版本的瀏覽器和 node.js 中執行的程式碼,這些程式碼當前都不支援 ECMAScript 6 模組。當前版本的 SystemJS 預設使用並需要 traceur,因此我們需要安裝它,但 SystemJS 可以配置為使用 traceur,babel 或 typescript(在某些外掛的幫助下)。
新增示例程式碼
建立檔案 test.js
:
import moment from 'moment';
export function test() {
const m1 = moment().format('LLL');
const m2 = moment().fromNow();
return `The moment is ${m1}, which was ${m2}`;
}
這是一個非常簡單的 javascript 模組,它還表明除了 import
和 export
之外你還可以使用其他新的 ECMAScript 6 功能。
在 node.js 中執行它
建立檔案 main.js
var SystemJS = require('systemjs');
SystemJS.config({
map: {
'traceur': 'node_modules/traceur/bin/traceur.js',
'moment': 'node_modules/moment/src'
},
packages: {
'moment': {
main: 'moment.js'
}
}
});
SystemJS.import('./test.js')
.then(function(test) {
var t = test.test();
console.log(t);
})
.catch(function(e) {
console.error(e)
});
這個檔案使用 SystemJS.import
載入我們的 test.js
檔案並從中執行 test()
函式,而不是普通的 require
。必須使用 SystemJS.config()
配置 SystemJS,以便找到 traceur
和 moment
模組的原始碼。map
中 moment
的路徑指向 moment/src
目錄,其中 ECMAScript 6 版本的 moment.js 原始碼所在。
你可以使用執行此檔案
node main.js
在瀏覽器中執行它
建立檔案 index.html
<html>
<head>
<title>SystemJS example with moment.js</title>
<meta charset="UTF-8">
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script>
SystemJS.config({
map: {
'traceur': 'node_modules/traceur/bin/traceur.js',
'moment': 'node_modules/moment/src'
},
packages: {
'moment': {
main: 'moment.js'
}
}
});
SystemJS.import('./test.js')
.then(function(test) {
var t = test.test();
document.body.appendChild(
document.createTextNode(t)
);
})
.catch(function(e) {
console.error(e)
});
</script>
</head>
<body>
</body>
</html>
與 node.js
程式碼的唯一區別是我們使用 <script>
標籤而不是 require
載入 SystemJS,我們使用 appendChild
將文字新增到 HTML 文件而不是在控制檯中顯示。