How to create global variables accessible in all views using Express / Node.JS?

前端 未结 8 1058
半阙折子戏
半阙折子戏 2020-11-28 01:53

Ok, so I have built a blog using Jekyll and you can define variables in a file _config.yml which are accessible in all of the templates/layouts. I am currently

8条回答
  •  渐次进展
    2020-11-28 02:17

    What I do in order to avoid having a polluted global scope is to create a script that I can include anywhere.

    // my-script.js
    const ActionsOverTime = require('@bigteam/node-aot').ActionsOverTime;
    const config = require('../../config/config').actionsOverTime;
    let aotInstance;
    
    (function () {
      if (!aotInstance) {
        console.log('Create new aot instance');
        aotInstance = ActionsOverTime.createActionOverTimeEmitter(config);
      }
    })();
    
    exports = aotInstance;
    

    Doing this will only create a new instance once and share that everywhere where the file is included. I am not sure if it is because the variable is cached or of it because of an internal reference mechanism for the application (that might include caching). Any comments on how node resolves this would be great.

    Maybe also read this to get the gist on how require works: http://fredkschott.com/post/2014/06/require-and-the-module-system/

提交回复
热议问题