New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Comments
Issue Type: Bug
I’m seeing a lint error after copying (some code in View Raw, in the browser) and pasting into a new document.
The error:
Expected linebreaks to be ‘LF’ but found ‘CRLF’.eslint(linebreak-style)
A Quick Fix is offered, but no matter if I attempt to apply to one line or all lines with the problem it is never resolved and the error persists.
VS Code version: Code 1.35.1 (c7d83e57cd18f18026a8162d042843bda1bcf21f, 2019-06-12T14:30:02.622Z)
OS version: Windows_NT x64 10.0.17763
System Info
Item | Value |
---|---|
CPUs | Intel(R) Core(TM) i5-8500 CPU @ 3.00GHz (6 x 3000) |
GPU Status | 2d_canvas: enabled checker_imaging: disabled_off flash_3d: enabled flash_stage3d: enabled flash_stage3d_baseline: enabled gpu_compositing: enabled multiple_raster_threads: enabled_on native_gpu_memory_buffers: disabled_software rasterization: enabled surface_synchronization: enabled_on video_decode: enabled webgl: enabled webgl2: enabled |
Load (avg) | undefined |
Memory (System) | 15.80GB (8.77GB free) |
Process Argv | |
Screen Reader | no |
VM | 0% |
Extensions (9)
Extension | Author (truncated) | Version |
---|---|---|
react-hooks-snippets | AlD | 1.1.5 |
open-html-in-browser | cod | 0.1.21 |
vscode-eslint | dba | 1.9.0 |
todo-tree | Gru | 0.0.138 |
svn-scm | joh | 1.54.3 |
intellij-idea-keybindings | k— | 0.2.33 |
start-git-bash | McC | 1.2.1 |
js-jsx-snippets | sky | 0.3.0 |
vscode-maven | vsc | 0.17.1 |
I still believe it is a bug to offer a Quick Fix and not have that fix work, but seconds after posting this Bug Report I noticed in the very bottom right of VS Code, only when focused on my new file, there is ‘CLRF’.
I then selected all in the file and clicked ‘CLRF’ and the setting toggled to ‘LF’.
That fixed my file.
daniel9212, pgcan, kotik-spb, SargisCH, xiaoai-li, davelsan, kiran-bhalerao, mudavel, randonia, ospira, and 4 more reacted with laugh emoji
dbnapp, bruceba22, zorek9502, mikelyons, rmar72, ilkerkaran, codecranium, KR78, SargisCH, xiaoai-li, and 12 more reacted with hooray emoji
mikelyons, ymzust, rmar72, ilkerkaran, burakozalp, SargisCH, xiaoai-li, Bidfca, metacoding, Relequestual, and 15 more reacted with heart emoji
mikelyons, rmar72, gordyclint, KR78, msully725, SargisCH, xiaoai-li, AnandKuhar1100, ekwholesale, kiran-bhalerao, and 4 more reacted with rocket emoji
dbaeumer
transferred this issue from microsoft/vscode
Jul 6, 2019
I’ve been trying to fix this for the past day and your comment saved me.
In my set up I have eslint and prettierjs plugins installed. I’ve tried toggling all different settings but none of them would fix this issue. Prettier would format the entire file but the crlf problem would remain. Clicking the quick-fix
option would also have no effect.
Thankfully my project is small so this wasn’t a problem to change every file’s setting to LF
.
Also you need to change the following setting so that newly created files will have LF
:
mcascone, VivienneB, NastyJoey, miguelcol29, leticiamrosa, Rony20191, and gabriellemos reacted with hooray emoji
Rony20191 reacted with rocket emoji
LF problem in a JS file.
Quick fix attempts to fix the problem, I can see the page refresh, but the file remains unix/LF.
Quick fix works with other ESLinting issues.
Manually selecting the EOL sequence from the status bar to CRLF changes the file to windows/CRLF and fixes the issue.
Ok so try ESLint from the command line: eslint --fix
Where eslintrc.js
linebreak-style
rules: { 'linebreak-style': ['error', 'windows'], // changes the file to CRLF }
rules: { 'linebreak-style': ['error', 'unix'], // changes the file to LF }
I hope this has been helpful
lrbtz, koraytug, JonathasGoncalves, mannnq, calmsz, aspirantzhang, haroldSanchezb, and saisanthosh09 reacted with hooray emoji
danchenko-a, AlexSegen, adsulemann, luizsantoszup, biswaranjanb, ethan-sbi, xvodddwannaG, lrbtz, tonicprism, koraytug, and 15 more reacted with heart emoji
The underlying problem here is that VS Code abstracts the line ending away (it is basically an array of lines) and hence it is not obvious on how to manipulate the line endings. Need to dig deeper.
You can use an .editorconfig for specifying line endings
And use the code-eol
extension to visualize the end of line.
@dbaeumer — if the code-eol
plugin can do it, I think the information is available somewhere.
I was having the same problem the CRLF/LF toggle does not work. This can occur when ‘n’ is a literal rather than an LF character. Open the file. Select CTRL+H, Select the .* (regex) to the right of the search bar. Select any ‘n’ literal in your open file. You should see \n in the search bar. In the replace bar enter n. Select replace all. This should do the trick for you. You’ll notice the files to include bar. You can perform this global search and replace for all relevant files.
Remains an issue.
Also, if I have an extra semi, then while removing the semi, vscode-eslint will double up each line ending to create blank lines.
By the way: running «eslint . —fix» fixes the problem just fine. May help someone trying to fix their project.
Я все еще считаю, что предлагать быстрое исправление — это ошибка, и это исправление не работает, но через несколько секунд после публикации этого отчета об ошибке я заметил в самом нижнем правом углу VS Code, только когда я сосредоточился на моем новом файле, есть ‘CLRF’ .
Затем я выделил все в файле и щелкнул «CLRF», и параметр переключился на «LF».
Это исправило мой файл.
thank you))
Solutions
Add in rules
"linebreak-style": [0 ,"error", "windows"],
If you need to know the principle, please see the following
Principle
When many people have different editors, VCs applications, and operating systems, different end of line writes may occur by any of the above
Line breaks in different systems
The newline character used in Windows operating system is usually a carriage return character (CR), followed by a newline character (LF), which makes it a carriage return newline character (CRLF)
Linux UNIX uses the simple line feed (LF). The corresponding control sequences are “[n] for LF and” [R] n “for CRLF
Many version control systems, such as GIT and subversion, can automatically ensure the correct outcome. But to cover all unexpected situations, you can activate this rule (linebreak style)
linebreak-style
this rule enforces a uniform end of line, independent of the operating system, VCs, or editors used throughout the code base
Options
“UNIX” (default) forces the use of UNIX line endings for LF
“windows” enforces the use of the windows line terminator for CRLFunix
Error examples
"unix"(Default) Force Unix line endings: n for LF.
"windows" forces the use of Windows line terminators: rn for CRLF.
Correct example
/*eslint linebreak-style: ["error", "unix"]*/
var a = 'a', // n
b = 'b'; // n
// n
function foo(params) { // n
// do stuff n
}// n
windows
Wrong Example
/*eslint linebreak-style: ["error", "windows"]*/
var a = 'a'; // n
Correct example
*eslint linebreak-style: ["error", "windows"]*/
var a = 'a', // rn
b = 'b'; // rn
// rn
function foo(params) { // rn
// do stuff rn
} // rn
use this rule in version control system
For example, the default behavior of GIT on Windows systems is to convert lf newline to CRLF when checking out a file, but store the newline as lf when committing changes. Linebreak style if this “UNIX” setting is configured, this will cause the rule to report an error because the file seen by eslint will have a CRLF newline character. If you use git, you can add a line to your. Gitattributes file to prevent git from converting line breaks in. JS files
*.js text eol=lf
Similar Posts:
При использовании eslint в проекте gulp я столкнулся с проблемой с ошибкой, подобной этой |
Expected linebreaks to be 'LF' but found 'CRLF' linebreak-style
, и я использую среду Windows для запуска gulp, и весь журнал ошибок приведен ниже.
Kiran (master *) Lesson 4 $ gulp
Using gulpfile c:UsersSaiDesktopweb-build-tools4
gulpfile.js
Starting 'styles'...
Finished 'styles' after 17 ms
Starting 'lint'...
'lint' errored after 1.14 s
ESLintError in plugin 'gulp-eslint'
sage: Expected linebreaks to be 'LF' but found 'CRLF'.
ails: fileName: c:UsersSaiDesktopweb-build-tools4jsextra.js
$>UsersSaiDesktopweb-build-tools4jsextra.js
error Expected linebreaks to be 'LF' but found 'CRLF' linebreak-style
У меня также есть файл extra.js как ошибка, указывающая на возможную ошибку.
function getWindowHeight() {
return window.innerHeight;
}
getWindowHeight();
Ответ 1
Проверьте, настроено ли правило linebreak-style
, как указано ниже, в вашем .eslintrc или в исходном коде:
/*eslint linebreak-style: ["error", "unix"]*/
Поскольку вы работаете с Windows, вы можете использовать это правило вместо:
/*eslint linebreak-style: ["error", "windows"]*/
Обратитесь к документации linebreak-style
:
При разработке с большим количеством людей, имеющих разные редакторы, VCS приложений и операционных систем, может случиться, что другая строка окончания написаны одним из упомянутых (особенно происходят при использовании окон и версий Mac SourceTree вместе).
Линейные строки (новые строки), используемые в операционной системе Windows, обычно возврат каретки (CR), за которым следует подача строки (LF), что делает ее (CRLF), тогда как Linux и Unix используют простой (LF). Соответствующие контрольные последовательности
"n"
(для LF) и"rn"
для (CRLF).
Это правило, которое автоматически фиксируется. Параметр --fix
в командной строке автоматически исправляет проблемы, описанные в этом правиле.
Но если вы хотите сохранить CRLF
концы строк в своем коде (поскольку вы работаете в Windows), не используйте параметр fix
.
Ответ 2
Я нашел его полезным (где я хотел проигнорировать линейные каналы и не изменять какие-либо файлы), чтобы игнорировать их в .eslintrc, используя стиль linebreak в соответствии с этим ответом: fooobar.com/questions/131045/…
module.exports = {
extends: 'google',
quotes: [2, 'single'],
globals: {
SwaggerEditor: false
},
env: {
browser: true
},
rules:{
"linebreak-style": 0
}
};
Ответ 3
Если вы используете vscode и используете Windows, я бы порекомендовал вам щелкнуть параметр в правом нижнем углу окна и установить для него значение LF из CRLF. Потому что мы не должны отключать конфигурацию только ради устранения ошибок в Windows
Если вы не видите LF/CLRF, щелкните правой кнопкой мыши строку состояния и выберите «Редактор конца строки».
Ответ 4
Просто сделали autocrlf
параметров в файле .gitconfig false
и клонировал код. Это сработало!
[core] autocrlf = false
Ответ 5
Произошло со мной, потому что я запустил git config core.autocrlf true
и забыл вернуться обратно.
После этого, когда я извлекаю/извлекаю новый код, все LF (разрыв строки в Unix) заменяется на CRLF (разрыв строки в Windows).
Я запустил linter, и все сообщения об ошибках Expected linebreaks to be 'LF' but found 'CRLF'
Чтобы решить эту проблему, я проверил значение autocrlf
, запустив git config --list | grep autocrlf
git config --list | grep autocrlf
и я получил:
core.autocrlf=true
core.autocrlf=false
Я отредактировал глобальную конфигурацию GIT ~/.gitconfig
и заменил autocrlf = true
на autocrlf = false
.
После этого я пошел в свой проект и сделал следующее (предполагая код в папке src/
):
CURRENT_BRANCH=$(git branch | grep * | cut -d ' ' -f2);
rm -rf src/*
git checkout $CURRENT_BRANCH src/
Ответ 6
Если вы используете vscode, я бы порекомендовал вам щелкнуть опцию в правом нижнем углу окна и установить для нее значение LF из CRLF. Это исправило мои ошибки.
Ответ 7
Если вы используете WebStorm и работаете в Windows, я бы порекомендовал вам щелкнуть вкладку «Настройки»/»Редактор»/»Стиль кода»/»Общие» и выбрать «Windows ( rn)» из выпадающего меню. Эти шаги также применимы к Rider.
Ответ 8
Если вы хотите это в crlf (Windows Eol), перейдите в Файл → Настройки → Настройки. Введите «конец строки» на вкладке «Пользователь» и убедитесь, что для Files: Eol установлено значение rn, а если вы используете расширение Prettier, убедитесь, что Красивее: Конец строки имеет значение crlf. Наконец, в свой файл eslintrc добавьте это правило:
'linebreak-style': ['error', 'windows']