【发布时间】:2018-10-10 06:10:29
【问题描述】:
我正在尝试学习如何制作 NPM 包,我认为这很容易:使用对象文字创建 JS 文件,导出模块,然后在另一端,让用户需要该文件并使用该对象: objectname.method。问题是我的目标用户将使用我的库来制作 html5 游戏。我没有制作客户端应用程序的经验,并且不真正了解在没有这些方法的情况下如何导入和请求文件。
我将如何做到这一点? 我想我可以像 nodeJS 一样通过 module.exports = {}
创建文件我正在尝试导出的对象的示例。老实说,我是在开玩笑,所以它可能是完全错误的。
//modEx.js
module.exports = {
drawBall: (ctx, x, y, ballRadius) => {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
},
hello: function() {
return "HELLO";
}
};
然后我通过尝试在另一个文件中导入/要求并打开带有脚本标签的 html 文件来进行测试。
//example.js
const mod_ex = require("./mod_ex");
console.log('hello',mod_ex.hello); #=> hello, undefined
【问题讨论】:
-
如果没有检查 Browserify 或 Webpack 的错误,您无法在浏览器中执行此操作。
标签: javascript html npm