Using require without export

后端 未结 3 1253
轻奢々
轻奢々 2021-02-05 01:26

I have this code (which works perfectly well) which I\'ve borrowed from an online resource:

var express = require(\'express\');
var bodyParser = require(\'body-p         


        
3条回答
  •  我寻月下人不归
    2021-02-05 02:21

    Besides requiring a module that doesn't include exports to run it's side effects it's also possible for a module to define variables in the global scope which can be accessed in the file where the module is required. This happens by defining variables without the var keyword. It's not a good or common practice, but you might encounter it somewhere so it's good to know what is going on.

    Example:

    // foo.js
    bar = 5;
    

    And

    // test.js
    require('./foo');
    
    console.log(bar);
    // prints 5
    

    If barwas defined as:

    var bar = 5;
    

    it would be in the module scope and not be accessible in test.js.

提交回复
热议问题