首页 > 解决方案 > Express:使用 UglifyJS 从远程 URL 缩小 CSS/JS

问题描述

我设法在#1 上获取数据,但无法在 Express #2 中打印出来,如何解析数据并输出?

我相信这是我的代码错误,我无法放置正确的异步/等待。

这是我的代码:

缩小.js

const { getContent } = require('./get');
const { minifyJS } = require('./processing');

async function getMinify(req, res) {
  try {
    const remoteUrl = 'http://example.com/script.js';

    console.log('URL: ' + remoteUrl);

    // #1
    const content = await getContent(remoteUrl);

    // #2
    const outputJS = await minifyJS(content);
    res.end(outputJS);

  } catch (error) {
    res.end(error.content);
  }
}

module.exports = { getMinify }

获取.js

const got = require('got');

async function getContent(remoteUrl) {
  const code = await got(remoteUrl);
  return code.body;
}

module.exports = { getContent }

处理.js

const { minify } = require('uglify-js');

async function minifyJS(data) {
  const result = await minify(data);

  return result.code;
}

module.exports = { minifyJS }

应用程序.js

const express = require('express');
const { getMinify } = require('./minify');

const app = express();

app.get('/*', getMinify);

app.listen(5000);

标签: node.jsexpress

解决方案


基于uglify-jsminify(data)函数的结果有两个对象codeerror.

并且minify(data)不需要await

processing.js应该改变

const { minify } = require("uglify-js");
async function minifyJS(data) {
  let { error, code } = minify(data);
  if (error) 
    throw error;
    
  return code;
}
module.exports = { minifyJS };

并为处理两个 .js 文件(get.js 和 processing.js)更改了 minify.js

  try {
    const remoteUrl = 'http://example.com/script.js';

    console.log('URL: ' + remoteUrl);

    // #1
    const content = await getContent(remoteUrl);

    // #2
    const outputJS = await minifyJS(content);
    res.end(outputJS);

  } catch (error) {
    res.end(error); // remove .content
  }

推荐阅读