简体   繁体   English

为浏览器和节点创建 npm 包

[英]Creating npm package for both browser and node

I'm trying to create an npm package that could be used by web apps or other node modules.我正在尝试创建一个可由网络应用程序或其他节点模块使用的 npm 包。

If I were to only support browsers, I would just assign to window window.myExport = myExport;如果我只支持浏览器,我会分配给窗口window.myExport = myExport; (unless there's a more modern way I'm not aware of?). (除非有一种我不知道的更现代的方式?)。

If I were to only support node modules, I would just use export, module.exports = myExport;如果我只支持节点模块,我会使用 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;

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.这是一个非常轻量级的节点模块,所以除非不可避免,否则我不想引入像 webpack 之类的构建器。 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.我已经在使用 babel 创建我的代码的 es5 兼容版本,所以如果 babel 可以为我解决这个问题,那就行得通了。

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.如果有人已经在使用 npm 来管理他们的依赖关系,那么假设他们将使用 webpack 或 browserify 之类的东西来允许他们导入/需要模块是合乎逻辑的。 It would be unusual for someone to download a library from NPM and manually include it in their page.有人从 NPM 下载库并手动将其包含在他们的页面中是不寻常的。 I would also consider it a gross violation for an npm library to add itself to the window object.我还认为 npm 库将自身添加到窗口对象是一种严重的违规行为。 This could cause all sorts of issues especially if different versions of your library are included on the same page.这可能会导致各种问题,尤其是当您的库的不同版本包含在同一页面上时。

The real question is ES module exports or commonJS exports.真正的问题是 ES 模块导出或 commonJS 导出。 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.其中我目前更喜欢 CommonJS,因为 ES 模块还没有在 nodejs 中原生实现,所以你必须使用 babel 来轻松导入它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM