gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:21:18 25 4
gpt4 key购买 nike

我实际上正在做的是编写一个 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/

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