1

I have a two variables defined in the webpack.config.js file that I want to populate with values from outer file called Web.config. For this outer file I have an npm package called just webconfig to parse the variables and it works. File is parsed async so the problem is with creating the module.exports properly.

const webconfig = require("webconfig");

let WEB_API_URL = 'a';
let WEB_APP_URL = 'b';

webconfig
    .compile({
        sources: [
            __dirname + '/Web.config'
        ]
    })
    .then(config => {
        WEB_API_URL = config.appSettings['__API_URL__'];
        WEB_APP_URL = config.appSettings['__APP_URL__'];
    });

 module.exports = {
//...
 plugins: [
        new webpack.DefinePlugin({
            __API_URL__: JSON.stringify(WEB_API_URL),
            __APP_URL__: JSON.stringify(WEB_APP_URL)
        })
}

Right now, the defined properties are exported as 'a' and 'b'. Can't find how to export the parsed properties from file. Any suggestions?

lkurylo
  • 1,621
  • 33
  • 59
  • You are missunderstanding how async code works. WEB_API_URL will only have a result when the promise resolves, and when the export is stated, the promise might not have been resolved yet. – PlayMa256 May 28 '18 at 11:49
  • I know very well why I don't get the proper values. What I'm asking is how to state the export after the promise is resolved, going by your nomenclature. I tried to move the entire module.export into the then part, but is ends with an error. – lkurylo May 28 '18 at 12:19
  • Try async-await, it stops the execution until you have a result. – PlayMa256 May 28 '18 at 12:29

2 Answers2

0

Finally I got it to work:

    module.exports = () => {
        let config = webconfig
            .compile({
                sources: [
                    __dirname + '/Web.config'
                ]
            });

        return config.then(data => {
            return {
//...
                plugins: [
                    new webpack.DefinePlugin({
                        __API_URL__: JSON.stringify(data.appSettings.__API_URL__),
                        __APP_URL__: JSON.stringify(data.appSettings.__APP_URL__)
                    })
                ]
            }
        });
    };
lkurylo
  • 1,621
  • 33
  • 59
0

I have hierarchy of configs, so promises would be everywhere to support async webpack calls

Resolve this with deasync

var webconfig = require("webconfig");

var result;
function getWebConfig() {
    webconfig
        .compile({
            sources: getConfigFilenames(),
        })
        .done(function (compiledWebConfig) {
            result = compiledWebConfig;
        });
}

getWebConfig();

while (result === undefined) {
    // Use sync call of async function
    require('deasync').runLoopOnce();
}
module.exports = result;
MarkosyanArtur
  • 1,359
  • 13
  • 10