// calculator.js
var calculator = {
add: function (a, b) {
return a + b;
},
subtract: function (a, b) {
return a - b;
}
};
module.exports = calculator;
此頁說明如何將 JavaScript 模組包含到 ClojureScript 專案中。請記住,本指南中描述的功能仍被視為 alpha 版本。
除了程式碼最佳化和相依性管理之外,Google Closure 編譯器還可以將常見的 JavaScript 模組轉換為 Google Closure 模組。擁有 Google Closure 模組而不是 JavaScript 模組具有以下優勢:
Google Closure 模組會納入原始碼最佳化
無需指定外部定義
接下來,我們將了解如何將以下簡單的 CommonJS 模組包含到 ClojureScript 專案中。
// calculator.js
var calculator = {
add: function (a, b) {
return a + b;
},
subtract: function (a, b) {
return a - b;
}
};
module.exports = calculator;
如果您想將 JavaScript 模組包含到您的專案中,您需要將其新增為外部程式庫,並使用 :module-type
編譯器選項指定其模組類型。目前支援的模組類型有 CommonJS、AMD 和 ECMAScript 6。分別地,可以為 :module-type
編譯器選項指定的值為 :commonjs
、:amd
和 :es6
。例如,上面顯示的 CommonJS 模組的編譯器選項如下:
:foreign-libs [{:file "resources/libs/calculator.js"
:provides ["calculator"]
:module-type :commonjs}]
您可以使用您為模組指定的名稱 (使用 :provides
編譯器選項) 將 JavaScript 模組包含到 ClojureScript 命名空間中。對於上面顯示的 CommonJS 模組,我們已指定名稱 calculator
。現在,我們可以在 ClojureScript 程式碼中使用該模組,就像使用來自Google Closure 程式庫的模組一樣。
(ns my-project.core
(:require [calculator :as calc]))
(enable-console-print!)
(println (calc/add 4 5))
當使用最佳化等級 :simple
或 :advanced
時,Google Closure 編譯器希望其 JavaScript 輸入符合一些限制。這表示如果您想使用其中任一最佳化等級,您的 JavaScript 模組必須符合 Google Closure 編譯器施加的限制。有關限制的更多詳細資訊,請參閱https://developers.google.com/closure/compiler/docs/limitations。
如果您的 JavaScript 模組依賴於其他模組,您也需要將這些模組新增至專案設定。對於具有許多不同模組的大型專案,這可能是不可行的。在這種情況下,您可能需要嘗試先捆綁您的專案,然後將其作為單一模組包含。
Node.js 模組規範與CommonJS 規範略有不同,因為傳遞給 require()
的模組識別符號不一定需要是絕對或相對路徑。這使得 Google Closure 編譯器難以解析節點模組的相依性,因為編譯器是按照標準的 CommonJS 規範實作的。因此,節點模組可能無法轉換為 Google Closure 模組。