javascript - 将异步加载的数据传递给 webpack 中的 pug-html-loader

标签 javascript node.js webpack pug-loader

一般设置

我正在基于这个很棒的样板文件使用 webpackpug 构建一个小型网站: 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/

相关文章:

javascript - 在组件中导入 LESS 文件

javascript - 如何根据不同的服务器端状态异步加载React组件?

javascript - ExtJs - 如何使用包含模型配置的 json 文件动态创建 Ext.data.Model 的实例

javascript - 错误 : "Cannot find module" while running firebase cloud function

javascript - getElementsByName 返回名称错误的元素

node.js - 我有 TypeError [ERR_INVALID_CALLBACK] : Callback must be a function

javascript - 我无法将 req.params.id 的输入使用到其他文件中存在的函数中

javascript - 无法在 React 中获取数组状态值

javascript - JavaScript 中的数字选择器

javascript - 触摸外部输入时在移动设备上保持键盘打开