简体   繁体   English

我如何为“linebreak-style”编写 ESLint 规则,根据 Windows 或 Unix 进行更改?

[英]How can I write a ESLint rule for "linebreak-style", changing depending on Windows or Unix?

As we all know, the linebreaks (new line) used in Windows are usually carriage returns (CR) followed by a line feed (LF) ie (CRLF) whereas, Linux and Unix use a simple line feed (LF)众所周知,Windows中使用的换行符(新行)通常是回车符(CR)后跟换行符(LF)即(CRLF),而Linux和Unix使用简单的换行符(LF)

Now, in my case, my build server uses supports Linux and Unix format so, below rule is working perfectly on build server:现在,就我而言,我的构建服务器使用支持 Linux 和 Unix 格式,因此,以下规则在构建服务器上完美运行:

linebreak-style: ["error", "unix"]

But I am doing development on Windows and I need to update rule on each git pull/git push as below,但我正在 Windows 上进行开发,我需要更新每个git 拉/git 推的规则,如下所示,

linebreak-style: ["error", "windows"]

So, is there any way to write a generic linebreak-style rule to support both environments, Linux/Unix and Windows?那么,有什么方法可以编写通用的换行符样式规则来支持 Linux/Unix 和 Windows 这两种环境?

Note : I am using ECMAScript6[js], WebStorm[ide] for development注意:我正在使用 ECMAScript6[js]、WebStorm[ide] 进行开发

Any solutions/suggestions would be highly appreciated.任何解决方案/建议将不胜感激。 Thanks!谢谢!

I spent time trying to find how to shut off the linkbreak-style and lost it due to reverting some of my code I thought others my like to have this as well.我花了一些时间试图找到如何关闭链接中断样式并由于还原我的一些代码而丢失了它,我认为其他人也喜欢这样做。

In the .eslintrc file you can also set linebreak-style to 0 which shuts off the linebreak feature:.eslintrc文件中,您还可以将linebreak-style设置为0以关闭行功能:

module.exports = {
  extends: 'google',
  quotes: [2, 'single'],
  globals: {
    SwaggerEditor: false
  },
  env: {
    browser: true
  },
  rules:{
    "linebreak-style": 0   // <----------
  }
};

The eslint configuration file can be a regular .js file (ie, not JSON, but full JS with logic) that exports the configuration object. eslint 配置文件可以是导出配置对象的常规.js文件(即不是 JSON,而是带有逻辑的完整 JS)。

That means you could change the configuration of the linebreak-style rule depending on your current environment (or any other JS logic you can think of).这意味着您可以根据当前环境(或您能想到的任何其他 JS 逻辑)更改换linebreak-style规则的配置。

For example, to use a different linebreak-style configuration when your node environment is 'prod':例如,当您的节点环境为“prod”时,要使用不同的linebreak-style配置:

module.exports = {
    "root": true,
    "parserOptions": {
        "sourceType": "module",
        "ecmaVersion": 6
    },
    "rules": {
        // windows linebreaks when not in production environment
        "linebreak-style": ["error", process.env.NODE_ENV === 'prod' ? "unix" : "windows"]
    }
};

Example usage:示例用法:

$ NODE_ENV=prod node_modules/.bin/eslint src/test.js

src/test.js
  1:25  error  Expected linebreaks to be 'CRLF' but found 'LF'  linebreak-style
  2:30  error  Expected linebreaks to be 'CRLF' but found 'LF'  linebreak-style
  3:36  error  Expected linebreaks to be 'CRLF' but found 'LF'  linebreak-style
  4:26  error  Expected linebreaks to be 'CRLF' but found 'LF'  linebreak-style
  5:17  error  Expected linebreaks to be 'CRLF' but found 'LF'  linebreak-style
  6:50  error  Expected linebreaks to be 'CRLF' but found 'LF'  linebreak-style
  7:62  error  Expected linebreaks to be 'CRLF' but found 'LF'  linebreak-style
  8:21  error  Expected linebreaks to be 'CRLF' but found 'LF'  linebreak-style

✖ 8 problems (8 errors, 0 warnings)

$ NODE_ENV=dev node_modules/.bin/eslint src/test.js
$ # no errors

In your .eslintrc.js :在您的.eslintrc.js

"rules": {
  "linebreak-style": ["error", (process.platform === "win32" ? "windows" : "unix")], // https://stackoverflow.com/q/39114446/2771889
}

See also: How do I determine the current operating system with Node.js另请参阅: 如何使用 Node.js 确定当前操作系统

.eslintc for Windows visualstudio code .eslintc 用于 Windows visualstudio 代码

 { "env": { "node": true }, "rules":{ "linebreak-style": 0 } }

A better option更好的选择

.editorconfig end_of_line .editorconfig end_of_line

Add the end_of_line rule in .editorconfig file:.editorconfig文件中添加end_of_line规则:

[*]
end_of_line= lf

EditorConfig is an extension for most code editors nowadays that changes the contents of the file you just saved . EditorConfig是当今大多数代码编辑器的扩展,它可以更改您刚刚保存的文件的内容 This rule enforces that all line endings are always unix consistent ( \n ) each time a developer saves a file (note: MacOs no longer uses \r => cr ).此规则强制每次开发人员保存文件时所有行结尾始终是unix 一致的( \n )(注意: MacOs 不再使用\r => cr )。 For enforcing windows line endings ( \r\n ) use crlf .对于强制Windows行尾( \r\n )使用crlf

This option is preferable since it avoids all line ending changes to be recorded in the project's repository (version control).此选项更可取,因为它避免了将所有行结束更改记录在项目的存储库中(版本控制)。

Not so optimal options...不是那么理想的选择...

As an EditorConfig note mentions:正如EditorConfig 注释所述:

if you want to use native line endings between different OSes, it is better not to set this option and leave that task to the VCS!如果您想在不同操作系统之间使用本机行尾,最好不要设置此选项并将该任务留给 VCS! In the future we might add a value like native for this scenario (cf #226 ).将来我们可能会为此场景添加一个像 native 这样的值(参见#226 )。

This would be a replacement for the accepted answer 's solution:这将替代接受的 answer的解决方案:

"linebreak-style": process.env.NODE_ENV === 'prod' ? "unix" : "windows"

Which is still better than completely disabling the rule ( "linebreak-style": 0 ): developers/contributors inconsistently may use their preferred line endings in the same file...这仍然比完全禁用规则更好( "linebreak-style": 0 ):开发人员/贡献者不一致地可能在同一个文件中使用他们喜欢的行结尾......

If you're using Vs Code on Windows, go to your ".eslintrc.json" file (or '.js' depending on which option you chose when setting up your ESLint);如果您在 Windows 上使用 Vs Code,请转到“.eslintrc.json”文件(或“.js”,具体取决于您在设置 ESLint 时选择的选项); this file will usually be found in the root folder of your project;该文件通常位于项目的根文件夹中; and under rules add the linebreak option to use Windows CRLF as follows:并在规则下添加换行选项以使用 Windows CRLF,如下所示:

"rules": {
    "linebreak-style": ["error", "windows"]
}

Save the file and when you go back to your JavaScript file, all those pesky red lines will disappear.保存文件,当您返回 JavaScript 文件时,所有那些讨厌的红线都会消失。

There are a few answers playing around with .eslintrc and one even suggest switching off the rule altogether.有一些与.eslintrc的答案,其中一个甚至建议完全关闭该规则。

However, what I prefer is to change VCS settings to checkout LF instead of CRLF .但是,我更喜欢将 VCS 设置更改为结帐LF而不是CRLF Assuming even in windows env, modern IDE should handle LF just fine.假设即使在 windows 环境中,现代 IDE 也应该可以很好地处理LF The drawback is some windows software like notepad aren't going to like it.缺点是像记事本这样的一些 Windows 软件不会喜欢它。 But this way you will be warned if you have incorrect linebreak style.但是这样,如果您的换行样式不正确,您将收到警告。 And it is less likely for people to commit incorrect linebreak style even if their VCS is misconfigured.即使他们的 VCS 配置错误,人们也不太可能提交不正确的换行样式。 Simply run git config --global core.autocrlf false or follow instructions on How do I force git to use LF instead of CR+LF under windows?只需运行git config --global core.autocrlf false或按照如何强制 git 在 Windows 下使用 LF 而不是 CR+LF 的说明进行操作?

Anyway, turning off the rule is discouraged in general as this will impact other team members, unless you have all of team's consent.无论如何,通常不鼓励关闭规则,因为这会影响其他团队成员,除非您得到团队的所有同意。

In my case, VS code had default settings of line break CRLF , because it was freshly installed.就我而言, VS 代码的默认设置为 line break CRLF ,因为它是新安装的。 I had to go to change that by: Ctrl + Shift + P to open the command palette and search for:我不得不去改变它: Ctrl + Shift + P打开命令面板并搜索:

Change for line endings更改行尾

There you can switch it to LF .在那里你可以将它切换到LF

The location of the config file required to alter ESLint rules for linebreak-style may change depending on whether you want to alter local, project or global settings, it searches for local first which overrides those further up the tree, so alter at the top of the tree to propagate down for global更改换行样式的 ESLint 规则所需的配置文件的位置可能会根据您是要更改本地、项目还是全局设置而改变,它首先搜索本地,这会覆盖树上更远的那些,所以在顶部进行更改为全局向下传播的树

I used airbnb style and my global settings were located here: node_modules/eslint-config-airbnb-base/rules/style.js:我使用了 airbnb 样式,我的全局设置位于此处:node_modules/eslint-config-airbnb-base/rules/style.js:

If you are unsure on the location of the file you can always search for a list of files that contain text relating to the settings, on Linux to find all files with linebreak settings navigate to the folder where ESLint was installed and use:如果您不确定文件的位置,您可以随时搜索包含与设置相关的文本的文件列表,在 Linux 上查找所有具有换行设置的文件,导航到安装 ESLint 的文件夹并使用:

grep -r linebreak

The "endOfLine": "auto" setting in .eslintrc.js and .prettierrc files worked for me. .eslintrc.js.prettierrc文件中的"endOfLine": "auto"设置对我有用。

File .eslintrc.js should have:文件.eslintrc.js应该有:

rules: {
    /*  ...the other code is omitted for the brevity */
    'arrow-body-style': [1, 'as-needed'],
    'import/extensions': 'off',
    'prettier/prettier': [
        'error',
        {
            semi: false,
            singleQuote: true,
            useTabs: true,
            endOfLine: 'auto', /* this setting should be included */
        },
    ],

File .prettierrc should have:文件.prettierrc应该有:

{
    "semi": false,
    "trailingComma": "all",
    "singleQuote": true,
    "useTabs": true,
    "tabWidth": 2,
    "endOfLine": "auto" /* this setting should be included */
}

If you want to set it up for all linux/unix, mac and windows, just replace the linebreak-style in eslintrc.json to "linebreak-style": ["error","unix | windows"]如果你想为所有linux/unix、mac和windows设置它,只需将eslintrc.json中的linebreak-style替换为"linebreak-style": ["error","unix | windows"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在ESlint中强制执行“换行样式”规则有多重要? 我可以关掉它吗? - How important is to enforce the “linebreak-style” rule in ESlint? Can I just turn it off? 预期换行符为“LF”但发现“CRLF”换行符样式 - Expected linebreaks to be 'LF' but found 'CRLF' linebreak-style 我可以在 eslint 配置中编写自己的自定义规则吗? - Can I write my own custom rule in eslint config? 如何为未定义规则设置陪同规则? - How can i set an eslint rule for no-undefined? 如何让 eslint 检测 JSON 文件中的规则违规? - How can I make eslint detect rule violations in JSON files? 如何切换到不同的ESLint样式指南? - How can I switch to a different ESLint style guide? 如果div为空,则Eslint airbnb gets强制执行自我关闭div标签。 如何禁用此规则? - Eslint airbnb gets enforces self closing div tag if the div is empy. How can I disable this rule? 如何在没有节点的情况下获取自定义eslint规则来执行context.report? - How can I get a custom eslint rule to do context.report without having a node? 更改布局-如何改变样式? - Changing layout -how can I style this differently? 如何在 Windows OS 中使用 TIMING=1 eslint 测量规则性能 - How to use TIMING=1 eslint to measure rule Performance in Windows OS
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM