eslint-config-formidable icon indicating copy to clipboard operation
eslint-config-formidable copied to clipboard

[DISCUSS] Relax func-style and no-use-before-define to enable idiomatic ES6 module patterns

Open jevakallio opened this issue 8 years ago • 4 comments

The following is an idiomatic ES6 pattern for structuring module code

// named export functions declared on top to make it easy
// to discover the public API exposed by the module
export function namedPublicMethod() {
  // do things
  return privateHelperFunction();
}

// less often read private utility functions declared on the bottom of the file
function privateHelperFunction() {
  // do things
}

The following rules prevent usage of this pattern:

"func-style": ["error", "expression"],
"no-use-before-define": "error"

And forces instead:

// private utility functions declared at the top of the file
const privateHelperFunction = function privateHelperFunction() {
  // do things
}

// forced usage of function expression with duplicated 
// variable name and named function expression
export const namedPublicMethod = function namedPublicMethod() {
  // do things
  return privateHelperFunction();
}

While the duplication of name is not strictly necessary, it is needed for readable stack traces in plain JavaScript environments. Whether or not Babel automatically generates the function expression names for anonymous functions based on variable name (it does), in vanilla environments it won't, and depending on a transpilation side-effect is brittle.

jevakallio avatar Oct 10 '16 18:10 jevakallio

Another common pattern prevented by no-use-before-define is this idiomatic React Native convention:

class SomeComponent extends React.Component {
  render() {
    return <View style={styles.container}>{...}</View>
  }
}

// styles defined in the bottom of the file
const styles = {
  container: {
    // ...
  }
}

And forces us to define the styles in a separate file (break co-location) or at the top of the file (makes code files hard to read by requiring to first scroll through screenful(s) of style definitions to get tho the component).

jevakallio avatar Oct 10 '16 18:10 jevakallio

I always make this change on my projects, so I am very much in favor of this change. 💯

divmain avatar Oct 11 '16 18:10 divmain

@jevakallio PR Welcome!

baer avatar May 16 '17 09:05 baer

{ "no-use-before-define": ["error", { "variables": false }] } This will keep that rule enabled for other things, such as classes and functions, but will relax it for variables.

rfdc avatar Aug 09 '18 11:08 rfdc