replaceEnv.js 1021 B

12345678910111213141516171819202122232425262728293031323334353637
  1. const fs = require('fs');
  2. const path = require('path');
  3. // 同步读取文件内容
  4. function readFileSync(filePath) {
  5. return fs.readFileSync(filePath, 'utf8');
  6. }
  7. // 同步写入文件内容
  8. function writeFileSync(filePath, data) {
  9. fs.writeFileSync(filePath, data, 'utf8');
  10. }
  11. // 替换文件中的文本
  12. function replaceTextInFileSync(filePath, matchKey, str) {
  13. try {
  14. // 读取文件内容
  15. let fileContent = readFileSync(filePath);
  16. // 替换文本
  17. const newContent = fileContent.replace(matchKey, str);
  18. // 写入新内容到文件
  19. writeFileSync(filePath, newContent);
  20. console.log('文本替换完成。');
  21. } catch (error) {
  22. console.error('文本替换失败:', error);
  23. }
  24. }
  25. // 使用示例
  26. const filePath = path.resolve('./src/assets/style/_variables.scss'); // 替换为你的文件路径
  27. const matchKey = '$main: #2ABED1;'; // 替换为需要查找并替换的文本
  28. const str = '$main: #111;'; // 替换为新的文本
  29. // replaceTextInFileSync(filePath, matchKey, str);