当我需要全局 html-minifier 时,为什么使用 minify 函数 returns Promise { <pending> } 而不是 HTML?

Why the minify function returns Promise { <pending> } instead of the HTML when I require a global html-minifier?

我不想一次又一次地安装节点模块所以我找到了一个 post here.

它使用 npm link 让我需要全局包。

但是,当我使用该方法时,html-minifier-terser 无法正常工作。 minify 函数 returns Promise { <pending> } 而不是 HTML.

但它与相同的 build.js 一起工作正常,而在该项目中,pughtml-minifier-terser 是由 npm install 而不是 npm install -g

代码如下:

const fs = require('fs');
// Compile the source code
const pug = require('pug');
// Compile the source code


buildFile('index');

function buildFile(filename) {

  var fs_content = fs.readFileSync(`./data/page-${filename}.json`);
  var options = JSON.parse(fs_content);

  const compiledFunction = pug.compileFile(`./pugs/${filename}.pug`,{});

  // Render a set of data
  var pug_html = (compiledFunction(options)); // this works fine.
  var minify = require('html-minifier-terser').minify;
  var result = minify(pug_html, {
    removeAttributeQuotes: true,
    minifyJS:true,
    minifyCSS:true,
    removeComments:true,
    collapseWhitespace:true,
    collapseInlineTagWhitespace:true
  });
  console.log(result); // Returns Promise { <pending> } instead of the HTML
}

更新:

我试过 await 但也失败了:

  var result = await minify(pug_html, {
               ^^^^^

SyntaxError: await is only valid in async function
    at new Script (vm.js:79:7)
    at createScript (vm.js:251:10)
    at Object.runInThisContext (vm.js:303:10)

可能是异步函数,你需要做

var result = await minify(pug_html, {
    removeAttributeQuotes: true,
    minifyJS:true,
    minifyCSS:true,
    removeComments:true,
    collapseWhitespace:true,
    collapseInlineTagWhitespace:true
  });

使用 await 关键字,使其“等待”函数的响应

看到这个link to learn more about promises. Essentially, you must wait for minifyJS to return the HTML by waiting for it (using .then((arg)=>{}). Also see the bottom of this readme

  minify(pug_html, {
    removeAttributeQuotes: true,
    minifyJS:true,
    minifyCSS:true,
    removeComments:true,
    collapseWhitespace:true,
    collapseInlineTagWhitespace:true
  }).then((res) => {result = res});