Javascript require()从包含的文件中运行不需要的命令
当我在文件顶部使用require()时,它会执行我包含的文件。我是不是误解了这个函数的工作原理?有没有办法让它不这样做 thing.jsJavascript require()从包含的文件中运行不需要的命令,javascript,Javascript,当我在文件顶部使用require()时,它会执行我包含的文件。我是不是误解了这个函数的工作原理?有没有办法让它不这样做 thing.js var hello = "helloworld"; var hello2 = "hello2world"; module.exports = {hello, hello2}; console.log(module.exports); console.log("if this is printing, it's not working"); printth
var hello = "helloworld";
var hello2 = "hello2world";
module.exports = {hello, hello2};
console.log(module.exports);
console.log("if this is printing, it's not working");
printthing.js
var msg = require('./thing.js');
console.log(msg.hello);
我只想把它打印出来
helloworld
但是我得到的是第一个文件和helloworld的输出
{ hello: 'helloworld', hello2: 'hello2world' }
if this is printing, it's not working
helloworld
导入
thing.js
时,将执行其中的所有行。因此,
module.exports和“如果这是打印,它不工作”
将首先打印,然后打印msg.hello
。导入thing.js时,将执行其中的所有行。因此,
module.exports
和“如果这是打印,它不工作”
首先打印,然后打印msg.hello
。由于语言的工作方式,当您导入
模块时,模块中的代码都会运行,即使您只想访问一个导出的符号,也不要将语句直接放在模块中;将它们放在函数/方法中。由于语言的工作方式,当您导入模块时,模块中的代码都会运行,即使您只想访问一个导出的符号。只是不要将语句直接放在模块中;将它们放在函数/方法中。