Search code examples
webpackweb-configwebpack-plugin

set variables by webpack.DefinePlugin from outer file - issues with async read


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?


Solution

  • 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__)
                        })
                    ]
                }
            });
        };