node.js - 在 NodeJS 中的另一个文件中引用全局 JS 函数

标签 node.js

我实际上正在做的是编写一个 VS Code 扩展,但由于我是 Node 新手,所以我很难从一个 JS 文件引用另一个文件。

//main.js (compiled from TypeScript)

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
require("./Test.js");
console.log("hello");
t1();

//Test.js

function t1() {
    console.log("t1");
}

它们都在同一个文件夹中。如果我从 VS Code 运行它,或者直接从 Node 运行它,它不起作用

PS E:\VSCodeTest> node src/main.js
hello
E:\VSCodeTest\src\main.js:5
t1();
^

ReferenceError: t1 is not defined
    at Object.<anonymous> (E:\VSCodeTest\src\main.js:5:1)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Function.Module.runMain (module.js:676:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3

VS Code 项目实际上是 TypeScript,但我已将其提炼为 JS 文件中问题的症结所在。

我相信它应该基于

https://www.typescriptlang.org/docs/handbook/modules.html

Import a module for side-effects only Though not recommended practice, some modules set up some global state that can be used by other modules. These modules may not have any exports, or the consumer is not interested in any of their exports. To import these modules, use:

import "./my-module.js";

我怎么误解了?

最佳答案

Test.js 更改为:

//Test.js

function t1() {
    console.log("t1");
}

module.exports = t1;

然后在 main.js 中执行类似这样的操作:

const t1 = require("./Test.js");
t1(); // prints "t1"

文档中有很多有关模块如何工作的信息:https://nodejs.org/api/modules.html

或者,如果您希望 t1 成为全局变量,则将其分配给 Test.js 中的 global.t1:

//Test.js

global.t1 = function t1() {
    console.log("t1");
};

不过,如果你能避免的话,我不会建议这样做,因为人们建议尽可能避免全局变量

关于node.js - 在 NodeJS 中的另一个文件中引用全局 JS 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49888311/

相关文章:

javascript - 从具有异步功能的 Node.js 模块返回值

javascript - 使用 Node.js 访问 azure 表存储

html - 如何在 react 中禁用内容安全策略

javascript - 将 Jquery 数据发布到 Express

javascript - 在 Node.js 中维护 session

node.js - 访问引用 Node.js 中的 Key Vault 的 Azure 应用程序配置设置

javascript - 在异步代码中运行同步代码 - promise

javascript - 缩小nodejs服务器端代码有什么好处吗?

javascript - 即使我以 root 身份运行,npm 安装期间权限也被拒绝

html - 如何在没有exe的情况下在node js中将html转换为pdf