为浏览器和节点创建npm包 [英] Creating npm package for both browser and node

查看:53
本文介绍了为浏览器和节点创建npm包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个可以由Web应用程序或其他节点模块使用的npm软件包.

I'm trying to create an npm package that could be used by web apps or other node modules.

如果我仅支持浏览器,则只需将其分配给窗口 window.myExport = myExport; (除非有我不知道的更现代的方式?).

If I were to only support browsers, I would just assign to window window.myExport = myExport; (unless there's a more modern way I'm not aware of?).

如果仅支持节点模块,则只使用export, module.exports = myExport; (同样,如果我不知道有更好的方法,请告诉我).

If I were to only support node modules, I would just use export, module.exports = myExport; (again, if there's a better way I'm not aware of, please let me know).

但是我都希望支持.目前,我正在做的是

But I want to support both. Currently, what I'm doing is

var window, module;
if (window)
    window.myExport = myExport;
if (module)
    module.exports = myExport;

这看起来很丑陋,但目前为止仍然有效.有什么更好的方法?这是一个非常轻量级的节点模块,因此,除非不可避免,否则我不希望引入诸如webpack之类的构建器.我已经在使用babel来创建我的es5兼容版本的代码,因此,如果babel可以为我解决此问题,那将是可行的.

This looks very ugly, but works so far. What's a better approach? This is very lightweight node module, so I don't want to bring in some builder like webpack or something unless un-avoidable. I am already using babel though to create an es5 compatible version of my code, so if babel can solve this issue for me, that would work.

推荐答案

如果某人已经在使用npm来管理其依赖项,则可以合理地假设他们将使用webpack或browserify之类的东西来允许他们导入/需要模块.有人从NPM下载一个库并将其手动包含在他们的页面中是不寻常的.我也认为npm库将自身添加到window对象中是严重违反.这可能会引起各种问题,尤其是如果同一页面上包含库的不同版本.

If someone is already using npm to manage their dependencies than it is logical to assume that they will be using something like webpack or browserify that will allow them to import/require the module. It would be unusual for someone to download a library from NPM and manually include it in their page. I would also consider it a gross violation for an npm library to add itself to the window object. This could cause all sorts of issues especially if different versions of your library are included on the same page.

真正的问题是ES模块导出或commonJS导出.我目前偏爱CommonJS,因为ES模块尚未在Node.js中本地实现,因此您必须使用babel轻松导入它们.

The real question is ES module exports or commonJS exports. Of which I currently favor CommonJS because ES modules are not natively implemented in nodejs yet so you have to use babel to easily import them.

这篇关于为浏览器和节点创建npm包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆