json - 如何在 Windows 命令行上通过 html-minifier 将选项传递给 UglifyJS?

标签 json node.js cmd escaping minify

HTMLMinifier ( html-minifier ) (3.5.14) for Node.js (v8.11.1),使用 npm install html-minifier -g 安装,可以通过命令行运行 (Windows CMD),例如html-minifier --help 生成使用信息(摘录):

  Usage: html-minifier [options] [files...]

  Options:

    -V, --version                        output the version number

...

    --minify-js [value]                  Minify Javascript in script elements and on* attributes (uses uglify-js)

...

    -c --config-file <file>              Use config file
    --input-dir <dir>                    Specify an input directory
    --output-dir <dir>                   Specify an output directory
    --file-ext <text>                    Specify an extension to be read, ex: html
    -h, --help                           output usage information

选项 --minify-js [value] 依赖于 UglifyJS “压缩”传递给 html-minifier 的 HTML 文件中嵌入的 JavaScript。 UglifyJS 可以通过启用 Can uglify-js remove the console.log statements? 从 JavaScript 中删除 console.log() 函数调用 ( drop_console )选项(另见 pure_funcs)。

但是 --minify-js drop_console=true 没有效果,"uglify:{options:{compress:{drop_console:true}}}""compress:{pure_funcs:['console.log']}"

如何设置这样的选项,最好是通过 html-minifier 命令行(或者通过 config-file ,尽管它只是设置 "minifyJS": true)?

最佳答案

我非常接近。

我开始深入研究代码(安装在 %appdata%\npm\node_modules\html-minifier 中)以查看提供的选项会发生什么,即使用 console 添加调试输出。 log(xyz);(使用实际的调试器可能是更好的主意)。

所以,这是我的“踪迹”:

最后排在 https://github.com/kangax/html-minifier/blob/gh-pages/src/htmlminifier.js#L667 的位置options.minifyJS 在作为 var result = UglifyJS.minify(code, minifyJS);https://github.com/kangax/html-minifier/blob/gh-pages/src/htmlminifier.js#L680 中运行之前被处理.

但是我们的选项字符串 compress:{pure_funcs:['console.log']} 被清理了,因为它还不是一个对象,导致 {}

或者,在使用不同字符串的不同试验中,您可能会遇到错误 Could not parse JSON value '{compress:{pure_funcs:'console.log']}}'

至少它做到了这一点!但为什么它不起作用?

首先,现在是重新审视 JSON 规范的好时机:https://www.json.org/index.html

其次,查看字符串是否可以解析为有效的 JSON,例如使用 JSON.parse() 演示 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

第三,弄清楚如何通过 CMD 获取该字符串作为参数(转义双引号)。

最后,确保配置 UgliFyJS 的数据结构是正确的。这很容易,因为它被记录在案:https://github.com/mishoo/UglifyJS2#minify-options-structure

看,简单地用反斜杠转义双引号对我有用:

html-minfier ... --minify-js {\"compress\":{\"pure_funcs\":[\"console.log\"]}} ...

它在选项中正确显示为

...
{ compress:
   { pure_funcs: [ 'console.log' ],
...

关于json - 如何在 Windows 命令行上通过 html-minifier 将选项传递给 UglifyJS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49763248/

相关文章:

node.js - @types 有什么特殊含义吗?

javascript - angularjs - Grunt 服务给出 "spawn cmd ENOENT"错误

javascript - 通过 Ajax 调用将 JSON 传递给 WCF

javascript - 在单独的函数中使用通过 AJAX 检索的 JSON 数据

javascript - jQuery Ajax每个函数检查返回ID是否与前一个相同

node.js - 需要关于 Cheerio eq() 变量的建议

javascript - FormData 服务器端 NodeJS

postgresql - 如何通过 CLI 连接到 PostgreSQL?

python - 使用 Subprocess (Python) 发送 CMD 命令提示符

json - 如何解析/反序列化动态 JSON