[译] 🙏 请把 .gitattributes 加入你的项目
![[译] 🙏 请把 .gitattributes 加入你的项目](https://static.blogweb.cn/article/20e8c67aad514890b0934fac63400191.webp)
.gitattributes 文件允许你指定当执行 git commit
等 git 动作时,应该被 git 使用的文件和路径的属性(attributes)。
换句话说,每当一个文件被创建或保存,git 会按照这些属性所指定的自动化的保存文件。
属性之一是 eol (end of line) ,其用于配置文件的行尾。本文就以此谈论如何配置行尾,以便让即便跨仓库使用不同机器、操作系统的每一位开发者都能使用到同样的值。
⚔️ .gitattributes 能平息程序员之间的战火吗?
并非所有开发者都整齐划一,对于你在一台 Windows 主机上使用 Visual Studio Code 写的代码,下一次由 pull request 提交时可能就是在 MacOS 主机上的 Sublime Text 2 中开发完成的。
由于开发者使用不同的操作系统司空见惯,由此带来的每种操作系统处理行尾的方法也各不相同。在 Windows 系统中,对于行尾默认使用回车换行 CRLF(Carriage Return Line Feed);而 Linux/MacOS 则只使用换行 LF(Line Feed)。
肉眼看上去内容都是一样的,为什么要整这些幺蛾子呢🤔???
由此,如果你还使用了 prettier 并将 endOfLine 像这样设置的话:
{
"endOfLine": "lf"
}
使用 Windows 的开发者就会遭遇以下语法提示:
![[译] 🙏 请把 .gitattributes 加入你的项目](https://static.blogweb.cn/article/a6f080182b414469801be30885e41481.webp)
这就是 .gitattributes
应该出现并挽救局面的时刻了!
为新项目配置 .gitattributes
先在项目根目录创建一个 .gitattributes 文件,其内容为:
*.js eol=lf
*.jsx eol=lf
*.json eol=lf
在仓库中 commit 该文件并将改动 push 到服务器:
git add .
git commit -m "Added .gitattributes to repo"
git push
这样一来,当有人从该仓库中取得代码并创建或修改其文件时,默认正确的行尾将经由 git 被自动使用。
向既有项目加入 .gitattributes
同样按上一节中的方法创建 .gitattributes 文件。一旦该文件被推送到 git 服务器后,就要确保本地仓库是干净的且没有东西要提交。使用 git status
来看一下情况:
git status
注意: 如果仍有文件要 push 或 commit,请确保这些动作先被执行完或在执行下条命令之前被 stash 暂存。
GitAttributes Reset
git rm --cached -r .
git reset --hard
以上两条命令将会使用 .gitattributes 中新定义行结尾规则更新仓库文件。
任何更改,都将根据匹配的文件类型自动应用新的行结尾。
下一步就是周知团队伙伴或合作伙伴了,也要运行一下上面两条命令。
![[译] 🙏 请把 .gitattributes 加入你的项目](https://static.blogweb.cn/article/0b0e24276e9a4909a836cb02ccf5967c.webp)
现在,prettier 不会再为 CR 的问题频频抱怨了,所有开发者也能和平共处了! ☮️
--End--![[译] 🙏 请把 .gitattributes 加入你的项目](https://static.blogweb.cn/article/9fb6469e84264c578c210040f852199d.webp)
查看更多前端好文请搜索 fewelife 关注公众号 转载请注明出处
转载自:https://juejin.cn/post/6844904062987550733