gpt4 book ai didi

javascript - 为什么我需要每个文件上的所有模块?

转载 作者:搜寻专家 更新时间:2023-11-01 00:18:16 26 4
gpt4 key购买 nike

我经常看到的默认方法是:

// repeat this in all files
var express = require('express');
var mongoose = require('mongoose');
var async = require('async');
...

但在我的 NodeJS 应用程序中,我这样做:

// include this only on the server file
_express = require('express');
_mongoose = require('mongoose');
_async = require('async');
...

我更喜欢使用 _ 前缀来识别库/模块,我不使用 var 因为我不想重复所有包的要求/设置在我申请的每个文件上。

这样我就可以在 server.js 文件上只使用一次 require() 模块并在任何地方使用它。

这是个坏主意吗?

最佳答案

模块缓存在nodejs中。最佳做法是在需要的地方要求。

来自 node.js 文档:

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.

Multiple calls to require('foo') may not cause the module code to be executed multiple times. This is an important feature. With it, "partially done" objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles.

http://nodejs.org/api/modules.html

关于javascript - 为什么我需要每个文件上的所有模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25575440/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com