[英]How do I JS-Beautify recursively?
我在一個目錄和子目錄中有很多 HTML 文件。 我可以通過命令行執行js-beautify
命令,並希望將它遞歸地應用於所有這些文件。
我試過了
找 。 -name " .html" -type f | js-beautify -r
and
js-beautify -r | 找 。 -name " .html" -type f
但它不起作用。 但是,如果我給出類似js-beautify -r myfile.html
或js-beautify -r *.html
(如果是目錄中的所有文件但不在子目錄中),則 JS-beautify 確實有效
誰能告訴我應該如何管道這兩個命令?
但是,JS-beautify 確實有效......如果所有文件都在目錄中但不在子目錄中
您已經提到如果所有輸入文件都在同一目錄中,則 JS-beautify 可以工作。 您的命令可能不起作用,因為您傳遞了find
所有結果,這些結果可能包括來自不同目錄的輸入文件。
正如前面評論中提到的,您可以使用-exec
代替:
find . -type f -name "*.html" -exec js-beautify -r {} \;
較新版本的 GNU find
可能使用以下語法:
find . -type f -name "*.html" -exec js-beautify -r {} +
我遇到了類似的問題,並使用glob-run找到了一個簡單的跨平台解決方案:
npm i -g glob-run js-beautify
glob-run html-beautify -r **/*.html
不過,如果 js-beautify本身支持 globs那就太好了。
find+xargs 是要走的路。 它比使用 -exec 查找要快。
find . -name '*.html' | xargs js-beautify
如果由於某種原因,你的文件名中有空格,你會想要這樣做......
find . -name '*.html' -print0 | xargs -0 js-beautify
最后,如果由於某種奇怪的原因,js-beautify 不能處理多個參數,那么您需要告訴 xargs 一次只傳遞一個參數。 這與使用 -exec 選項沒有太大區別,但 IMO 更好,因為它更一致。
find . -name '*.html' | xargs -n 1 js-beautify
請注意,您可以將-print0
和xargs -0
選項與xargs -n 1
。
編輯:正如 TJ Crowder 所指出的,shell 不會在雙引號中使用通配符。 這對我來說是個新聞,也許有一些古老的環境並非如此,希望你永遠不會被迫在其中工作。
1)將這些依賴項添加到您的項目中
npm install --save-dev glob js-beautify
2) 創建scripts/format.js
const jsBeautify = require('js-beautify')['js_beautify'];
const fs = require('fs');
const glob = require('glob');
const options = {
indent_size: 2,
indent_char: ' ',
indent_with_tabs: false,
eol: '\n',
end_with_newline: true,
indent_level: 0,
preserve_newlines: true,
max_preserve_newlines: 10,
space_in_paren: false,
space_in_empty_paren: false,
jslint_happy: false,
space_after_anon_function: false,
brace_style: 'collapse',
break_chained_methods: false,
keep_array_indentation: false,
unescape_strings: false,
wrap_line_length: 0,
e4x: false,
comma_first: false,
operator_position: 'before-newline'
};
glob('**/!(node_modules)/**/*.js', { absolute: true }, (er, files) => {
files.forEach(file => {
console.log(`js-beautify ${file}`);
const data = fs.readFileSync(file, 'utf8');
const nextData = jsBeautify(data, options);
fs.writeFileSync(file, nextData, 'utf8');
});
});
3) 在package.json
添加format
腳本
"scripts": {
"format": "node ./scripts/format.js"
}
4)在你的項目中,運行
npm run format
結合上面比爾的智慧和這些關於正則表達式匹配的答案,這是我項目的實際解決方案:
找 。 -regextype egrep -regex './(src|test|app)/.*.(js|sass|html)' -print0 | xargs -0 ./node_modules/.bin/js-beautify -r
-r
)./node_modules/.bin
) 在 package.json 腳本中使用時, ./node_modules/.bin
自動在路徑中, \\.*
需要轉義為\\\\.*
,因此:
"beautify2": "find . -regextype egrep -regex './(src|test|app)/.*\\.(js|sass|html)' -print0 | xargs -0 js-beautify -r"
→
beautified app/index.html
beautified app/sass/_atomic.sass
beautified app/sass/_mixin.sass
beautified app/sass/space test.sass
beautified test/Log.test.js
beautified test/deleteAction.test.js
beautified src/util/fileUtils.js
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.