Search code examples
node.jsecmascript-6node-config

How can I hoist a variable above all imports in ES6?


Basically I'm using babel to transpile my nodejs app so I can use es6, as well as the node-config package.

The node-config package by default looks for configs in the /config folder. This is reassignable by doing something like this BEFORE config is loaded. process.env["NODE_CONFIG_DIR"] = __dirname + "/configDir/";

However, since I'm using ES6, imports are being hoisted and are always loading before any code is run.

I was wondering if there was a way I could hoist the above code above all imports so that it runs before node-config is loaded? Or if there is perhaps another way I can tackle this problem?

Any help is appreciated!


Solution

  • Since you are using Babel, you could write your own plugin that does whatever you need, like prepending that statement to the file where you need it.

    If you want to solve this in the source itself, notice that imports are executed in order, so you can do

    // main.js
    import './configure-node-config';
    import 'node-config';
    …
    
    // configure-node-config.js
    process.env["NODE_CONFIG_DIR"] = __dirname + "/configDir/";
    

    and be certain that process.env was mutated before node-config is loaded.