如何将匹配x的所有行移动到文件的顶部?



如何移动所有以(或包含)"@use"开头的代码行?放到文件的最上面?

.css-class {
@use 'text-size' as *; // How to move all lines starting with @use to the top of the file (Ideally alphabetizing them and removing duplicates as well)
@include text-size(lg);
font-weight: 500;
margin: 0;
text-align: left;
}
.another-css-class {
@use 'text-size' as *;
@include text-size(md);
font-weight: normal;
margin: 0;
text-align: left;
@use 'text-color' as *;
@include text-color(dark);
}
.yet-another-css-class {
@use 'background-color' as *;
@include background-color(teal, 20);
padding: 16px;
text-align: center;
}

理想的输出(删除重复和按字母顺序排列SASS导入的加分项)

@use 'background-color' as *;
@use 'text-color' as *;
@use 'text-size' as *; 

.css-class {
@include text-size(lg);
font-weight: 500;
margin: 0;
text-align: left;
}
.another-css-class {
@include text-size(md);
font-weight: normal;
margin: 0;
text-align: left;
@include text-color(dark);
}
.yet-another-css-class {
@include new--background-color(teal, 20);
padding: 16px;
text-align: center;
}

附加上下文:我已经有了遍历目录并逐行执行的代码,并在mixins使用(@include mixin-name();)之上添加了SASS导入(@use 'mixin-name' as *;)。理想情况下,我想把它添加到文件的顶部,但我没有任何运气。

我对不使用node的fs的其他解决方案持开放态度。

add-sass-imports.js

const fs = require('fs');
const replaceFile = (file) => {
const originalText = fs.readFileSync(file);
const lines = originalText.toString().split("n");
const formattedLines = lines.map((line, lineNumber) => {
const match = /.*@includes([a-zA-Z'-]+)[s(;]/.exec(line);
if (!match) return line; // don't change anything
const [, mixin] = match;
//instead of adding it above the line, I would like it to be placed to the top of the file (and remove duplicates)
return `@use '${mixin}' as *;
` + line;
});
fs.writeFileSync(file, formattedLines.join("n"));
};
const replaceInFolder = (path) => {
const content = fs.readdirSync(path);
content.forEach((fileOrFolder) => {
const fullPath = `${path}/${fileOrFolder}`;
const stat = fs.statSync(fullPath);
if (stat.isDirectory()) {
replaceInFolder(fullPath);
} else if (fileOrFolder.endsWith(".scss")) {
replaceFile(fullPath);
}
});
};
replaceInFolder("src/app")
for file in $(find . -name '*.scss')
do
grep '@uses' $file | sort -t: -k2,2 > $file.tmp
grep -v '@uses' $file >> $file.tmp
mv $file.tmp $file
done

这个grep代码可以工作。

注意:如果你使用zsh,你可以使用exec bash切换shell。

最新更新