抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

一、前言

1.1 背景

相信团队中同时存在 WindowsLinux/MacOS 的开发者时,经常会遇到 warning: LF will be replaced by CRLF 这个警告,特别是在前端项目中更是常见,例如配置了 eslint 规则检查,其中换行规则为 lf ,这时候 windows 同事克隆项目后打开会发现全是格式错误的提示。

1.2 现状一

网络上大部分文章可能是告诉你通过配置 core.autocrlf 参数来解决问题,例如

1
git config --global core.autocrlf false

此方法的确能解决问题,但是通过此方法只能是治标不治本,因为实际中你无法得知团队中其他开发者是否有配置,是否愿意配置,每次新人加入团队都得指导一次等等。

1.3 现状二

部分文章提到了通过 .gitattributes 来解决此问题,例如

1
*.* text eol=lf

但可能其作者是一知半解,或从其他地方借鉴来的文章,甚至没有经过自己实测,仅配置此项会带来其他问题,最常见的即 png 图片再本地可以正常查看,而提交之后文件就损坏,图片无法查看了。

二、解决方案

本文不详细介绍 .gitattributes 的作用及规范,具体可查看官方文档

需注意的是 .gitattributes 文件在提交后才能生效,因此在旧项目中,建议直接在git仓库中添加,而后重新克隆即可。

在根目录中添加 .gitattributes 文件,并自行选择一种方案。

2.1 方案一(较推荐)

参考自v8/v8,无后缀文件默认处理,有后缀文件默认为lf,最后再单独标记特定后缀文件为二进制文件不处理。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
* text=auto

# Force the following filetypes to have unix eols, so Windows does not break them
*.* text eol=lf

# Separate configuration for files without suffix
LICENSE text eol=lf

# These files are binary and should be left untouched
# (binary is a macro for -text -diff)
*.png binary
*.pdf binary
*.doc binary
*.docx binary
*.ppt binary
*.pptx binary
*.xls binary
*.xlsx binary
*.exe binary
# Add more binary...

2.2 方案二

参考自mozilla/pdf.js,一一为特定文件指定规则

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Force Unix line endings for most file formats (except binary files)
*.js text eol=lf
*.jsm text eol=lf
*.css text eol=lf
*.html text eol=lf
*.md text eol=lf
*.properties text eol=lf
*.yml text eol=lf
*.json text eol=lf
*.config text eol=lf
*.inc text eol=lf
*.manifest text eol=lf
*.rdf text eol=lf
*.jade text eol=lf
*.coffee text eol=lf

# PDF files shall not modify CRLF line endings
*.pdf binary
# Add more binary...

评论