[英]NodeJS: How can I include some javascript code snippet without using require?
I wanted to include some js files without using require because it would link it to a variable, and i have some functions i would like to call directly. 我想在不使用require的情况下包含一些js文件,因为它会将其链接到变量,并且我想直接调用一些函数。 how can i do it ?
我该怎么做 ? is it bad practice ?
这是不好的做法吗?
what i want to avoid is this: let's say i have tool.js as follow: 我要避免的是:假设我有如下的tool.js:
function foo() {
log.debug("foo");
}
exports.foo = foo;
in app.js 在app.js中
var tool= require('tools.js');
tool.foo();
i would like to be able to call foo without creating a module for it as if it was define in app.js; 我希望能够在不为其创建模块的情况下调用foo,就像在app.js中定义它一样; like so
像这样
foo();
You can require a file and use its functions without assigning it to a variable by using the global object. 您可以通过使用全局对象来要求文件并使用其功能,而无需将其分配给变量。
file1.js file1.js
function logger(){
console.log(arguments);
}
global.logger = logger;
file2.js file2.js
require('./file1');
logger('ABC');
This approach would get rid of variable scoping and would pollute the global namespace potentially leading to clashes with variable naming. 这种方法将摆脱变量作用域,并会污染全局名称空间,从而可能导致变量命名冲突。
You need to use global like this, 您需要像这样使用global
======= app.js ====== ======= app.js ======
global.foo= require('tools.js'); // declare as global
foo(); // can be called from all files
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.