简体   繁体   English

NodeJS:如何在不使用require的情况下包含一些javascript代码段?

[英]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.

相关问题 如何在NodeJS中使用功能和对象而不需要它们 - How can I use functions and objects without require them in NodeJS YUI,Javascript:如何优化此代码段以使其运行更快? - YUI,Javascript: How can i optimize this code snippet to run faster? 如何使用Tornado的self.write方法发送javascript代码段? - How can I send a code snippet of javascript using Tornado's self.write method? 如何在WordPress中包含/要求外国JavaScript库? - How can I include/require foreign JavaScript libraries in WordPress? 如何在PhpStorm中为我的JavaScript代码添加“ require”? - How to include “require” in PhpStorm for my JavaScript code? 如何避免在 Javascript 闭包中使用此代码段? - How can I avoid using this snippet in Javascript closures? 如何对该代码段进行单元测试? - How can I unit test this code snippet? 如何在当前的JavaScript代码段中“返回此”以满足调用者的链接而不会破坏我的ESLint规则? - How can I 'return this' in the current JavaScript snippet to cater for chaining in the caller without breaking my ESLint rules? 如何使用 VM 在 nodejs 中安全地运行用户代码而不会受到攻击 - How can I run user code securely in nodejs using VM without being vulnerable to attacks 如何在不影响使用 Nodejs 或 Javascript 的 HTML 标签的情况下从 HTML 中获取 100 到 200 个单词? - How can I get 100 to 200 words from HTML without affecting HTML tags using Nodejs or Javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM