【发布时间】:2021-11-27 18:00:11
【问题描述】:
如何将所有以“@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 *;) 的代码。理想情况下,我想将其添加到文件顶部,但没有任何运气。
我对其他不使用节点 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 = /.*@include\s([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")
【问题讨论】:
-
您编写了哪些代码来尝试满足此要求?你在哪里卡住?您可以将该代码共享为minimal reproducible example 吗?我们不是您的个人代码编写服务。 How to Ask
-
@esqew,我将代码附加到问题的底部。其中大部分来自一位同事,所以我问 permisison 是否可以将其包含在我的问题中。