nodejs require - 模块名称区分大小写的问题 [英] nodejs require - module name case sensitive issue

查看:732
本文介绍了nodejs require - 模块名称区分大小写的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我发现了一个关于node.js需要机制的奇怪问题

recently i found out a strange problem regarding the node.js require mechanism

您可能会认为,由于Windows文件系统,如果需要的模块是无关紧要的区分大小写。所以......

you might think, due to windows file system it doesn't matter if required modules are case sensitive or not. So ...

模块A:

require("fancyModule");

模块B:

require("fancymodule");

都指向同一个fancymodule.js文件。但该对象的构造函数将被调用两次。所以

are both leading to to the same fancymodule.js file. but the constructor of that object will be called twice. so

var FancyModule = {
    var name = "unkown";
    var setName = function(val){
        name = val
    }
    return {
        setName:setName
    }
}
module.exports = FancyModule();

将导致两个单独的FancyModule实例。所以请注意它。

will result into two separate FancyModule instances. so be aware of it.

我知道我总是要关心正确的文件名 - 无论文件系统是否区分大小写。

I know that i always have to care about the right file name - no matter if the file system is case sensitive or not.

我的问题是,
有没有办法设置或配置nodejs以防止这种情况 - 或者至少打印出警告?

my question is, is there any way to setup or configure nodejs to prevent that - or at least print out a warning ?

推荐答案

首先,永远不要对你正在使用的文件系统做出假设。
如果你在不同的环境中运行它,总是期望它区分大小写。

First of all, never make assumptions about the filesystem you are using. Always expect it to be case sensitive, in case you run it in a different environment.

现在你的问题:

当您需要节点中的模块时,节点将完全缓存导入以防止您要导出单例并且不将其初始化两次的情况。
虽然文件系统查找将返回相同的确切文件,因为它不区分大小写,但require缓存仍然将这两种情况视为不同的模块。那是因为它必须假设它在区分大小写的环境中运行,因此实际上可能有两个不同的模块。

When you require a module in node, node will cache the import exactly to prevent the case where you want to export a singleton and not have it initialized twice. While the filesystem lookup will return the same exact file because it's case insensitive, require's cache still treats the two cases as different modules. That's because it has to assume that it runs in a case sensitive environment, so there could actually be two different modules behind that.

这就是为什么它初始化你的单例两次。它实际上将它们视为两个不同的模块。

That's why it initializes your singleton twice. It actually treats them as two different modules.

您在询问是否有任何方法可以阻止它。
有一种非常容易但又可怕的方法。您可以修补 global.require 以小写您的导入:

You were asking if there's any way to prevent it. There is a very easy but horrible way to do it. You can patch global.require to lowercase your imports:

var patchRequire = function () {
    var oldRequire = global.require;
    global.require = function (moduleName) {
        return oldRequire.call(global, moduleName.toLowerCase());
    };
};

patchRequire();
require('Foo-Bar'); // Will require 'foo-bar' instead

但请不要这样做。最好确保保持导入的一致性,并使用以短划线分隔的所有小写名称。

But please don't do that. Better make sure to keep your imports consistent and use all lower case names separated by dashes.

这篇关于nodejs require - 模块名称区分大小写的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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