Preventing global installations of an NPM package

2019-04-01 00:57发布

问题:

I have a library and want to encourage/force users to use the locally installed version only. I could do this the hard way or the easy way.

The easy way would be if NPM had a mechanism to prevent using the --global switch with the npm install command, for any library.

The hard way would be to add code in my NPM packaged that returned early if the code determined it was globally installed not locally installed.

Does anyone know if you can prevent global installations of an NPM package? What might be the most user friendly way to approach this?

回答1:

The best way to prevent users from installing your module globally would be to describe your preference in the documentation.

There is nothing you can do to force your users to never install it globally if they can install it locally. They will always be able to move the files manually if they want.

In the npm community the assumption is that the user has control over the modules he/she uses, not the other way around. Forcing people to use your module in certain ways will only make them unhappy.

So the only good answer to your question is to document the way your code should be used. You can ask them to use your module a certain way - but they are the ones who can choose to listen to you or not. You can state that using your module installed globally is unsupported, unwise, discouraged, dangerous, but you will not be able to force users to use the module as you want, and that's a good thing.

Now, for some bad answers, you can always test if the parent of your module's root directory is named node_modules or not and fail if it isn't but I'm sure it can cause some trouble if someone happens to install your module locally as you want but under a different directory. You can see if your module is run from one of the default paths that node uses to search for modules but those paths are not always the same, and you'd have to take the NODE_PATH environment variable into account as well.

You can do few tricks like that but they can only annoy users who know what they are doing because they will have to change the source code of your module to do what they want, and they will always be able to do that, no matter how hard you try to make their life harder.

In summary, my recommendation would be to document your module well and respect your users and their needs, and trust them to know what they're doing.

Update

For a working example of a Bash function that prevents global npm installation of a certain module, see this answer - section Working example of preventing global install.



标签: node.js npm