提问人:Basj 提问时间:8/5/2022 最后编辑:Basj 更新时间:8/5/2022 访问量:122
创建具有 IIFE 命名空间的 JS 库
Creating a JS library with IIFE namespacing
问:
如果我们不想使用ES6或任何第三方库(如require.js等)或任何包构建器,那么打包库的经典方法是什么,以便用户可以将其与似乎是库命名空间一起使用?import
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
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 之前的解决方案感到好奇。
答:
1赞
Basj
8/5/2022
#1
解决方案似乎是:
// 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>
评论
es6
var window.canvas
会抛出错误,你必须这样做window.canvas = {}
window.myCanvas
canvas
window.myCanvas