一般设置
我正在基于这个很棒的样板文件使用 webpack 和 pug 构建一个小型网站: https://github.com/alexnoz/webpack-pug-scss-boilerplate.git
项目已启动并正在运行,我能够正确渲染哈巴狗文件。
要求
现在我需要在所有 webpack 编译发生之前加载一些数据。我想将该数据传递给 pug-html-loader,如 this answered question 中所述.
问题/疑问
我的问题是,我必须异步加载该数据。所以我有一个 promise 。我如何确保 promise 在 webpack 编译发生之前完成?
这是我目前行不通的方法
// in webpack.config.js
var myData = []
loadSomeDataAsync().then(loadedData => myData = loadedData)
{
loader: 'pug-html-loader',
options: {
data: myData // <====
}
}
pug-html-loader
接受 options.data
如果我把静态数据放在那里,那么这个数据在 pug 模板中是可用的。
我知道我的问题似乎是,在 webpack 编译发生之前,我的 Promise 尚未解决。但是如何让 webpack 以某种方式“等待”Promise 解析呢?
我已经尝试注册 webpack 事件 Hook 。但没有成功。还有什么建议吗?
最佳答案
这种情况的默认模式如下:
const configPromise = new Promise(function(resolve, reject) {
setTimeout(() => { resolve(webpackConfig) }, 1000);
});
configPromise
.then(webpack) // Passes the config to webpack
.then(compiler => {
// Do the work with the compiler
});
该功能在 DOCS 中有详细记录.
Webpack will run the function exported by the configuration file and wait for a Promise to be returned. Handy when you need to asynchronously load configuration variables.
module.exports = () => {
return new Promise((resolve, reject) => { // The promise could be an XHR call using fetch, Axios or whatever
setTimeout(() => {
resolve({ // Resolve webpack config
entry: './app.js',
/* ... */
});
}, 5000);
});
};
关于javascript - 将异步加载的数据传递给 webpack 中的 pug-html-loader,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57956482/