Skip to content

Commit

Permalink
Merge pull request #1135 from chrislloyd/issue-1123
Browse files Browse the repository at this point in the history
[no-relative-parent-imports] Resolve paths
  • Loading branch information
ljharb committed Jul 16, 2018
2 parents 5adebd8 + 81bf977 commit a162af4
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
20 changes: 17 additions & 3 deletions src/rules/no-relative-parent-imports.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import moduleVisitor, { makeOptionsSchema } from 'eslint-module-utils/moduleVisitor'
import docsUrl from '../docsUrl'
import { basename } from 'path'
import { basename, dirname, relative } from 'path'
import resolve from 'eslint-module-utils/resolve'

import importType from '../core/importType'

Expand All @@ -14,11 +15,24 @@ module.exports = {

create: function noRelativePackages(context) {
const myPath = context.getFilename()
if (myPath === '<text>') return {} // can't cycle-check a non-file
if (myPath === '<text>') return {} // can't check a non-file

function checkSourceValue(sourceNode) {
const depPath = sourceNode.value
if (importType(depPath, context) === 'parent') {

if (importType(depPath, context) === 'external') { // ignore packages
return
}

const absDepPath = resolve(depPath, context)

if (!absDepPath) { // unable to resolve path
return
}

const relDepPath = relative(dirname(myPath), absDepPath)

if (importType(relDepPath, context) === 'parent') {
context.report({
node: sourceNode,
message: 'Relative imports from parent directories are not allowed. ' +
Expand Down
25 changes: 25 additions & 0 deletions tests/src/rules/no-relative-parent-imports.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,18 @@ ruleTester.run('no-relative-parent-imports', rule, {
test({
code: 'import("./app/index.js")',
}),
test({
code: 'import(".")',
}),
test({
code: 'import("path")',
}),
test({
code: 'import("package")',
}),
test({
code: 'import("@scope/package")',
}),
],

invalid: [
Expand Down Expand Up @@ -69,5 +78,21 @@ ruleTester.run('no-relative-parent-imports', rule, {
column: 8,
} ],
}),
test({
code: 'import foo from "./../plugin.js"',
errors: [ {
message: 'Relative imports from parent directories are not allowed. Please either pass what you\'re importing through at runtime (dependency injection), move `index.js` to same directory as `./../plugin.js` or consider making `./../plugin.js` a package.',
line: 1,
column: 17
}]
}),
test({
code: 'import foo from "../../api/service"',
errors: [ {
message: 'Relative imports from parent directories are not allowed. Please either pass what you\'re importing through at runtime (dependency injection), move `index.js` to same directory as `../../api/service` or consider making `../../api/service` a package.',
line: 1,
column: 17
}]
})
],
})

0 comments on commit a162af4

Please sign in to comment.