简体   繁体   English

如何让一个npm package对多个JS模块可用?

[英]How to make an npm package available to multiple JS modules?

Context :上下文

I am transitioning from the traditional js/html way of doing frontend development:我正在从传统的 js/html 前端开发方式转变:

<script src="link-to-the-js-file"></script>

<!-- Now, just use the library... -->

To the modern npm/js-modules/webpack way:以现代的 npm/js-modules/webpack 方式:

npm install whatever

require('whatever')

whatever.doSomething();

Question :问题

I am confused about when and how to require packages that will be used in multiple modules.我对何时以及如何要求将在多个模块中使用的包感到困惑。

Let's say I have two features in my site for which I want to use axios .假设我的站点中有两个要使用axios的功能。

I would do:我会做:

file : feature.js文件feature.js

/**
 * Some JS module where I'll use axios
 */

const axios = require('axios');

export default () => ({
...

   axios.doWhatever();

...
});

But what if there is another module that also needs axios?但是如果有另一个模块也需要 axios 怎么办?

If I require it in another-file.js , won't I have axios included multiple times in my compiled JS?如果我在another- file.js 中需要它,我编译的 JS 中不会多次包含 axios 吗?

So this leads me to think... okay, I will attach it to the window scope and just use it from there whenever I want.所以这让我想到......好吧,我会把它附加到 window scope 并随时从那里使用它。

And go with something like:和 go 类似:

file : global-file.js文件全局文件.js

window.axios = require('axios');

But I don't know if this is good practice.但我不知道这是否是好的做法。

I know opinion based questions are not allowed here, but there must be a solid generic approach for this.我知道这里不允许基于意见的问题,但必须有一个可靠的通用方法。 I don't want to "just make it work", I want to do things in a correct manner.我不想“让它工作”,我想以正确的方式做事。 I'll appreciate your help.我会感谢你的帮助。

From the Node documentation:从节点文档:

Modules are cached after the first time they are loaded.模块在第一次加载后被缓存。 This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.这意味着(除其他外)每次调用require('foo')都会得到完全相同的 object 返回,如果它解析到同一个文件。

So you are basically (in most cases) using the same object/file.所以你基本上(在大多数情况下)使用相同的对象/文件。 But if you don't want to repeat yourself in multiple files you can just add it to the global scope like so:但是如果你不想在多个文件中重复你自己,你可以像这样将它添加到全局 scope 中:

axios = require('axios ');

See more on Node.js caching .查看更多关于Node.js 缓存的信息。

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

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