Skip to content

Commit

Permalink
Add rule with docs
Browse files Browse the repository at this point in the history
  • Loading branch information
tizmagik committed Aug 13, 2016
1 parent 4d23c24 commit 5c9d99d
Show file tree
Hide file tree
Showing 2 changed files with 93 additions and 0 deletions.
44 changes: 44 additions & 0 deletions docs/rules/max-dependencies.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# max-dependencies

Forbid modules to have too many dependencies (`import` or `require` statements).

This is a useful rule because a module with too many dependencies is code smell, and usually indicates the module is doing too much and/or should be broken up into smaller modules.

Importing multiple named exports from a single module will only count once (e.g. `import {x, y, z} from './foo'` will only count as a single dependency).

### Options

This rule takes the following option:

`max`: The maximum number of dependencies allowed. Anything over will trigger the rule. **Default is 10** if the rule is enabled and no `max` is specified.

You can set the option like this:

```js
"import/max-dependencies": ["error", {"max": 10}]
```


## Example

Given a max value of `{"max": 2}`:

### Fail

```js
import a from './a'; // 1
const b = require('./b'); // 2
import c from './c'; // 3 - exceeds max!
```

### Pass

```js
import a from './a'; // 1
const anotherA = require('./a'); // still 1
import {x, y, z} from './foo'; // 2
```

## When Not To Use It

If you don't care how many dependencies a module has.
49 changes: 49 additions & 0 deletions src/rules/max-dependencies.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import Set from 'es6-set'
import isStaticRequire from '../core/staticRequire'

const DEFAULT_MAX = 10

const countDependencies = (dependencies, lastNode, context) => {
const {max} = context.options[0] || { max: DEFAULT_MAX }

if (dependencies.size > max) {
context.report(
lastNode,
`Maximum number of dependencies (${max}) exceeded.`
)
}
}

module.exports = context => {
const dependencies = new Set() // keep track of dependencies
let lastNode // keep track of the last node to report on

return {
ImportDeclaration(node) {
dependencies.add(node.source.value)
lastNode = node.source
},

CallExpression(node) {
if (isStaticRequire(node)) {
const [ requirePath ] = node.arguments
dependencies.add(requirePath.value)
lastNode = node
}
},

'Program:exit': function () {
countDependencies(dependencies, lastNode, context)
},
}
}

module.exports.schema = [
{
'type': 'object',
'properties': {
'max': { 'type': 'number' },
},
'additionalProperties': false,
},
]

0 comments on commit 5c9d99d

Please sign in to comment.