replace-imports.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. const fs = require("fs");
  2. const path = require("path");
  3. const rootDir = path.resolve(__dirname, "./"); // 请替换为你的项目根目录
  4. function walk(dir, callback) {
  5. fs.readdirSync(dir).forEach((f) => {
  6. const dirPath = path.join(dir, f);
  7. const isDirectory = fs.statSync(dirPath).isDirectory();
  8. isDirectory ? walk(dirPath, callback) : callback(path.join(dir, f));
  9. });
  10. }
  11. function convertImportToUse(content, filePath) {
  12. // 匹配 @import "xxx"; 或 @import 'xxx';
  13. return content.replace(/@import\s+["']([^"']+)["'];/g, (match, importPath) => {
  14. // 如果是 CSS 文件(例如 @import 'element-plus/dist/index.css'),不替换
  15. if (importPath.endsWith('.css')) return match;
  16. // vue 文件中 style 标签内容需保留缩进,稍微兼容
  17. const indent = match.match(/^\s*/)?.[0] ?? '';
  18. return `${indent}@use "${importPath}" as *;`;
  19. });
  20. }
  21. walk(rootDir, (filePath) => {
  22. if (filePath.endsWith(".scss") || filePath.endsWith(".vue")) {
  23. const content = fs.readFileSync(filePath, "utf8");
  24. if (content.includes("@import")) {
  25. const newContent = convertImportToUse(content, filePath);
  26. if (newContent !== content) {
  27. fs.writeFileSync(filePath, newContent, "utf8");
  28. console.log("✔ Converted:", filePath);
  29. }
  30. }
  31. }
  32. });