通过外部文件中的webpack.DefinePlugin设置变量 - 异步读取问题

问题描述 投票:1回答:2

我在webpack.config.js文件中定义了两个变量,我想用外部文件中的值填充Web.config。对于这个外部文件,我有一个名为webconfig的npm包来解析变量并且它可以工作。文件被解析为异步,因此问题在于正确创建module.exports。

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)
        })
}

现在,已定义的属性将导出为“a”和“b”。找不到如何从文件中导出已解析的属性。有什么建议?

webpack web-config webpack-plugin
2个回答
0
投票

最后我得到了它的工作:

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

0
投票

我有配置的层次结构,所以承诺将到处支持异步webpack调用

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;
© www.soinside.com 2019 - 2024. All rights reserved.