Skip to content

Commit

Permalink
Implement extensions rule
Browse files Browse the repository at this point in the history
This fixes #209 and fixes #204.
  • Loading branch information
lo1tuma committed Apr 20, 2016
1 parent 60ceb16 commit 3fa81d2
Show file tree
Hide file tree
Showing 9 changed files with 279 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,12 @@ This plugin intends to support linting of ES2015+ (ES6+) import/export syntax, a
* Ensure all imports appear before other statements ([`imports-first`])
* Report repeated import of the same module in multiple places ([`no-duplicates`])
* Report namespace imports ([`no-namespace`])
* Ensure consistent use of file extension within the import path ([`extensions`])

[`imports-first`]: ./docs/rules/imports-first.md
[`no-duplicates`]: ./docs/rules/no-duplicates.md
[`no-namespace`]: ./docs/rules/no-namespace.md
[`extensions`]: ./docs/rules/extensions.md


## Installation
Expand Down
85 changes: 85 additions & 0 deletions docs/rules/extensions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# extensions - Ensure consistent use of file extension within the import path

Some file resolve algorithms allow you to omit the file extension within the import source path. For example the `node` resolver can resolve `./foo/bar` to the absolute path `/User/someone/foo/bar.js` because the `.js` extension is resolved automatically by default. Depending on the resolver you can configure more extensions to get resolved automatically.

In order to provide a consistent use of file extensions across your code base, this rule can enforce or disallow the use of certain file extensions.

## Rule Details

This rule has one option which could be either a string or an object. If it is `"never"` (the default value) the rule forbids the use for any extension. If `"always"` then the rule enforces the use of extensions for all import statements.

By providing an object you can configure each extension separately, so for example `{ "js": "always", "json": "never" }` would always enforce the use of the `.js` extension but never allow the use of the `.json` extension.

### Exception

When disallowing the use of certain extensions this rule makes an exception and allows the use of extension when the file would not be resolvable without extension.

For example, given the following folder structure:

```
├── foo
│   ├── bar.js
│   ├── bar.json
```

and this import statement:

```js
import bar from './foo/bar.json';
```

then the extension can’t be omitted because it would then resolve to `./foo/bar.js`.

### Examples

The following patterns are considered problems when configuration set to "never":

```js
import foo from './foo.js';

import bar from './bar.json';

import Component from './Component.jsx'

import express from 'express/index.js';
```

The following patterns are not considered problems when configuration set to "never":

```js
import foo from './foo';

import bar from './bar';

import Component from './Component'

import express from 'express/index';
```

The following patterns are considered problems when configuration set to "always":

```js
import foo from './foo';

import bar from './bar';

import Component from './Component'

import express from 'express';
```

The following patterns are not considered problems when configuration set to "always":

```js
import foo from './foo.js';

import bar from './bar.json';

import Component from './Component.jsx'

import express from 'express/index.js';
```

## When Not To Use It

If you are not concerned about a consistent usage of file extension.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@
"es6-set": "^0.1.4",
"es6-symbol": "*",
"eslint-import-resolver-node": "^0.2.0",
"lodash.endswith": "^4.0.1",
"object-assign": "^4.0.1"
}
}
1 change: 1 addition & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export const rules = {
'namespace': require('./rules/namespace'),
'no-namespace': require('./rules/no-namespace'),
'export': require('./rules/export'),
'extensions': require('./rules/extensions'),

'no-named-as-default': require('./rules/no-named-as-default'),
'no-named-as-default-member': require('./rules/no-named-as-default-member'),
Expand Down
66 changes: 66 additions & 0 deletions src/rules/extensions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import path from 'path'
import resolve from '../core/resolve'
import endsWith from 'lodash.endsWith'

module.exports = function (context) {
const configuration = context.options[0] || 'never'

function isUseOfExtensionEnforced(extension) {
if (typeof configuration === 'object') {
return configuration[extension] === 'always'
}

return configuration === 'always'
}

function isResolvableWithoutExtension(file) {
const extension = path.extname(file)
const fileWithoutExtension = file.slice(0, -extension.length)
const resolvedFileWithoutExtension = resolve(fileWithoutExtension, context)

return resolvedFileWithoutExtension === resolve(file, context)
}

function checkFileExtension(node) {
const { source } = node
const importPath = source.value
const resolvedPath = resolve(importPath, context)
const extension = path.extname(resolvedPath).substring(1)

if (!endsWith(importPath, extension)) {
if (isUseOfExtensionEnforced(extension)) {
context.report({
node: source,
message: `Missing file extension "${extension}" for "${importPath}"`,
})
}
} else {
if (!isUseOfExtensionEnforced(extension) && isResolvableWithoutExtension(importPath)) {
context.report({
node: source,
message: `Unexpected use of file extension "${extension}" for "${importPath}"`,
})
}
}
}

return {
ImportDeclaration: checkFileExtension,
}
}

module.exports.schema = [
{
oneOf: [
{
enum: [ 'always', 'never' ],
},
{
type: 'object',
patternProperties: {
'.*': { enum: [ 'always', 'never' ] },
},
},
],
},
]
1 change: 1 addition & 0 deletions tests/files/bar.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
1 change: 1 addition & 0 deletions tests/files/bar.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default null
1 change: 1 addition & 0 deletions tests/files/file.with.dot.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default null
121 changes: 121 additions & 0 deletions tests/src/rules/extensions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import { RuleTester } from 'eslint'
import rule from 'rules/extensions';
import { test } from '../utils';

const ruleTester = new RuleTester()

ruleTester.run('extensions', rule, {
valid: [
test({ code: 'import a from "a"' }),
test({ code: 'import dot from "./file.with.dot"' }),
test({
code: 'import a from "a/index.js"',
options: [ 'always' ]
}),
test({
code: 'import dot from "./file.with.dot.js"',
options: [ 'always' ]
}),
test({
code: [
'import a from "a"',
'import packageConfig from "./package.json"',
].join('\n'),
options: [ { json: 'always', js: 'never' } ]
}),
test({
code: [
'import lib from "./bar"',
'import component from "./bar.jsx"',
'import data from "./bar.json"'
].join('\n'),
options: [ 'never' ],
settings: { 'import/resolve': { 'extensions': [ '.js', '.jsx', '.json' ] } }
})
],

invalid: [
test({
code: 'import a from "a/index.js"',
errors: [ {
message: 'Unexpected use of file extension "js" for "a/index.js"',
line: 1,
column: 15
} ]
}),
test({
code: 'import a from "a"',
options: [ 'always' ],
errors: [ {
message: 'Missing file extension "js" for "a"',
line: 1,
column: 15
} ]
}),
test({
code: 'import dot from "./file.with.dot"',
options: [ "always" ],
errors: [
{
message: 'Missing file extension "js" for "./file.with.dot"',
line: 1,
column: 17
}
]
}),
test({
code: [
'import a from "a/index.js"',
'import packageConfig from "./package"',
].join('\n'),
options: [ { json: 'always', js: 'never' } ],
settings: { 'import/resolve': { 'extensions': [ '.js', '.json' ] } },
errors: [
{
message: 'Unexpected use of file extension "js" for "a/index.js"',
line: 1,
column: 15
},
{
message: 'Missing file extension "json" for "./package"',
line: 2,
column: 27
}
]
}),
test({
code: [
'import lib from "./bar.js"',
'import component from "./bar.jsx"',
'import data from "./bar.json"'
].join('\n'),
options: [ 'never' ],
settings: { 'import/resolve': { 'extensions': [ '.js', '.jsx', '.json' ] } },
errors: [
{
message: 'Unexpected use of file extension "js" for "./bar.js"',
line: 1,
column: 17
}
]
}),
test({
code: [
'import lib from "./bar.js"',
'import component from "./bar.jsx"',
'import data from "./bar.json"'
].join('\n'),
options: [ { json: 'always', js: 'never', jsx: 'never' } ],
settings: { 'import/resolve': { 'extensions': [ '.js', '.jsx', '.json' ] } },
errors: [
{
message: 'Unexpected use of file extension "js" for "./bar.js"',
line: 1,
column: 17
}
]
})

]
})

0 comments on commit 3fa81d2

Please sign in to comment.