[英]Creating a JS library with IIFE namespacing
如果我們不想使用 ES6 import
或任何第三方庫(如 require.js 等)或任何 package 構建器,那么打包庫的經典方法是什么,以便用戶可以使用它似乎是庫命名空間?
index.html
(從庫用戶的角度)
<canvas id="mycanvas"></canvas>
<script src="canvas.js"></script>
<script>
canvas.setup({"config1": true, "config2": false});
var mycanvas1 = canvas.get("#mycanvas");
</script>
我有時會看到類似於
// canvas.js
(function (window, something, else) {
window.canvas.setup = function() { ... } // how to export functions setup and get?
})(window, ..., ...);
如何正確執行此IIFE以創建此canvas.js
庫示例?
注意:使用 ES6 import
,我們可以通過 package 這種方式創建一個名為canvas.js
的庫:
const canvas = {
setup: config => { console.log("config"); },
get: id => { console.log("get"); }
};
export default canvas;
並以這種方式使用index.html
:
<canvas id="mycanvas"></canvas>
<script type="module">
import canvas from "./canvas.js";
canvas.setup({"config1": true, "config2": false});
var mycanvas1 = canvas.get("#mycanvas");
</script>
但是在這里的這個問題中,我對 ES6 之前的解決方案感到好奇。
一個解決方案似乎是:
// canvas.js
canvas = (function(window) { // assign the result of the IIFE to a global var to make
// it available for the user of the lib
var internal_variable; // not accessible to the user of the lib
var state; // this variable will be available to the user of the lib
function setup(arg) {
console.log("setup");
}
function get(arg) {
console.log("get"); // + other lines using window object
}
return {setup: setup, get: get, state: state}; // important: here we choose what we
// export as an object
})(window);
現在用戶可以通過這種方式使用庫:
<canvas id="mycanvas"></canvas>
<script src="canvas.js"></script> // object canvas is now available
<script>
canvas.setup({"config1": true, "config2": false});
var mycanvas1 = canvas.get("#mycanvas");
console.log(canvas.state);
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.