diff --git a/blog/git-crlf-lf-solution.md b/blog/git-crlf-lf-solution.md new file mode 100644 index 0000000..ddfc0c2 --- /dev/null +++ b/blog/git-crlf-lf-solution.md @@ -0,0 +1,127 @@ +--- +slug: git-crlf-lf-solution +title: "彻底解决 Windows 前端开发中的换行符问题" +authors: lxy +tags: [ Git, Prettier, 前端开发, 换行符 ] +--- + +## 背景 + +在 Windows 系统上进行前端开发时,通常使用 Git 进行版本控制,并使用 Prettier 进行代码格式化。跨平台协作中,不同操作系统对换行符的处理方式不同: + +- **CRLF**(`\r\n`):Windows 系统默认使用 +- **LF**(`\n`):Unix/Linux/Mac 系统使用 + +前端项目通常统一使用 LF 换行符,以保持代码一致性。 + +## 问题 + +在 Windows 上开发时,遇到以下问题: + +1. **Git 自动转换**:执行 `git pull` 后,文件行尾字符自动从 LF 变回 CRLF +2. **Prettier 报错**:格式化时提示 `Warning: Line endings should be LF, but CRLF found` +3. **配置无效**:即使配置了 `core.autocrlf=false` 也可能无效 + +## 解决方案 + +### 一、Prettier 配置 + +在 `.prettierrc` 或 `package.json` 中配置: + +```json +{ + "endOfLine": "lf" +} +``` + +批量修复现有文件: + +```bash +npx prettier --write "**/*.{js,jsx,ts,tsx,json,css,scss,md}" +``` + +### 二、Git 配置 + +### 1. 全局配置 + +```bash +git config --global core.autocrlf false +git config --global core.eol lf +``` + +### 2. 项目级配置(可选) + +```bash +git config core.autocrlf false +git config core.eol lf +``` + +### 3. 创建 .gitattributes 文件 + +在项目根目录创建 `.gitattributes`: + +``` +* text=auto eol=lf +*.sh text eol=lf +*.js text eol=lf +*.ts text eol=lf +*.json text eol=lf +*.md text eol=lf +*.yml text eol=lf +*.yaml text eol=lf +*.png binary +*.jpg binary +*.jpeg binary +*.gif binary +*.ico binary +*.pdf binary +``` + +### 4. 修复已存在的文件 + +```bash +git rm --cached -r . +git reset --hard +git add .gitattributes +git add -A +git commit -m "统一使用 LF 行尾字符" +``` + +### 5. 验证配置 + +```bash +# 查看配置 +git config --global --list | grep -E "autocrlf|eol" + +# 检查文件行尾 +git ls-files --eol +``` + +### 三、完整操作流程 + +按以下步骤执行: + +```bash +# 1. 全局配置 Git +git config --global core.autocrlf false +git config --global core.eol lf + +# 2. 创建 .gitattributes 文件(内容见上文) + +# 3. 修复现有文件 +git rm --cached -r . +git reset --hard +git add .gitattributes +git add -A +git commit -m "统一使用 LF 行尾字符" + +# 4. 使用 Prettier 格式化修复换行符 +npx prettier --write "**/*.{js,jsx,ts,tsx,json,css,scss,md}" +``` + +## 注意事项 + +- `.gitattributes` 优先级最高,会覆盖 `core.autocrlf` 和 `core.eol` 配置 +- 团队需要统一配置,避免不同开发者之间的冲突 +- 规范化操作会改变文件内容,团队成员需要重新拉取代码 +