Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript require()从包含的文件中运行不需要的命令_Javascript - Fatal编程技术网

Javascript require()从包含的文件中运行不需要的命令

Javascript 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

当我在文件顶部使用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");
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

由于语言的工作方式,当您
导入
模块时,模块中的代码都会运行,即使您只想访问一个导出的符号,也不要将语句直接放在模块中;将它们放在函数/方法中。由于语言的工作方式,当您导入模块时,模块中的代码都会运行,即使您只想访问一个导出的符号。只是不要将语句直接放在模块中;将它们放在函数/方法中。