javascript – How can I write a ESLint rule for linebreak-style, changing depending on Windows or Unix?

javascript – How can I write a ESLint rule for linebreak-style, changing depending on Windows or Unix?

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:

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.

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).

For example, to use a different linebreak-style configuration when your node environment is prod:

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

javascript – How can I write a ESLint rule for linebreak-style, changing depending on Windows or Unix?

In your .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

Leave a Reply

Your email address will not be published.