在NodeJS

时间:2018-04-17 22:19:01

标签: node.js

我实际上在做的是编写VS代码扩展,但由于我是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运行它,或直接从节点运行它,它不起作用

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“./ my-module.js”;

我怎么误解了?

2 个答案:

答案 0 :(得分:2)

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成为全局,请将其分配到global.t1中的Test.js

//Test.js

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

我不建议如果你可以避免它,但由于所有原因,人们建议尽可能避免使用全局变量

答案 1 :(得分:1)

要求不起作用,但是你很接近 - 如果你想在另一个文件中使用你创建的函数,只需将它添加到该文件的导出中。

/// test.js
exports.t1 = function() ...

// or

module.exports = {
  t1: function() ...
}

然后你需要专门保存它才能使用它

/// main.js
var t1 = require('./test.js').t1;

t1();

全局范围不像在浏览器中那样工作,请查看node's docstry a blog explaining it(我没有写这个并且不能完全担保)

相关问题