Coder Social home page Coder Social logo

import-js / eslint-plugin-import Goto Github PK

View Code? Open in Web Editor NEW
5.3K 37.0 1.5K 3.65 MB

ESLint plugin with rules that help validate proper imports.

License: MIT License

JavaScript 98.94% CoffeeScript 0.01% TypeScript 0.24% Shell 0.21% PowerShell 0.04% Batchfile 0.02% HTML 0.55%
eslint-plugin javascript import eslint code-quality linting lint hacktoberfest

eslint-plugin-import's Introduction

eslint-plugin-import

github actions travis-ci coverage win32 build status npm npm downloads

This plugin intends to support linting of ES2015+ (ES6+) import/export syntax, and prevent issues with misspelling of file paths and import names. All the goodness that the ES2015+ static module syntax intends to provide, marked up in your editor.

IF YOU ARE USING THIS WITH SUBLIME: see the bottom section for important info.

Rules

💼 Configurations enabled in.
⚠️ Configurations set to warn in.
🚫 Configurations disabled in.
❗ Set in the errors configuration.
☑️ Set in the recommended configuration.
⌨️ Set in the typescript configuration.
🚸 Set in the warnings configuration.
🔧 Automatically fixable by the --fix CLI option.
💡 Manually fixable by editor suggestions.
❌ Deprecated.

Helpful warnings

Name                       Description 💼 ⚠️ 🚫 🔧 💡
export Forbid any invalid exports, i.e. re-export of the same name. ❗ ☑️
no-deprecated Forbid imported names marked with @deprecated documentation tag.
no-empty-named-blocks Forbid empty named import blocks. 🔧 💡
no-extraneous-dependencies Forbid the use of extraneous packages.
no-mutable-exports Forbid the use of mutable exports with var or let.
no-named-as-default Forbid use of exported name as identifier of default export. ☑️ 🚸
no-named-as-default-member Forbid use of exported name as property of default export. ☑️ 🚸
no-unused-modules Forbid modules without exports, or exports without matching import in another module.

Module systems

Name                     Description 💼 ⚠️ 🚫 🔧 💡
no-amd Forbid AMD require and define calls.
no-commonjs Forbid CommonJS require calls and module.exports or exports.*.
no-import-module-exports Forbid import statements with CommonJS module.exports. 🔧
no-nodejs-modules Forbid Node.js builtin modules.
unambiguous Forbid potentially ambiguous parse goal (script vs. module).

Static analysis

Name                       Description 💼 ⚠️ 🚫 🔧 💡
default Ensure a default export is present, given a default import. ❗ ☑️
named Ensure named imports correspond to a named export in the remote file. ❗ ☑️ ⌨️
namespace Ensure imported namespaces contain dereferenced properties as they are dereferenced. ❗ ☑️
no-absolute-path Forbid import of modules using absolute paths. 🔧
no-cycle Forbid a module from importing a module with a dependency path back to itself.
no-dynamic-require Forbid require() calls with expressions.
no-internal-modules Forbid importing the submodules of other modules.
no-relative-packages Forbid importing packages through relative paths. 🔧
no-relative-parent-imports Forbid importing modules from parent directories.
no-restricted-paths Enforce which files can be imported in a given folder.
no-self-import Forbid a module from importing itself.
no-unresolved Ensure imports point to a file/module that can be resolved. ❗ ☑️
no-useless-path-segments Forbid unnecessary path segments in import and require statements. 🔧
no-webpack-loader-syntax Forbid webpack loader syntax in imports.

Style guide

Name                            Description 💼 ⚠️ 🚫 🔧 💡
consistent-type-specifier-style Enforce or ban the use of inline type-only markers for named imports. 🔧
dynamic-import-chunkname Enforce a leading comment with the webpackChunkName for dynamic imports.
exports-last Ensure all exports appear after other statements.
extensions Ensure consistent use of file extension within the import path.
first Ensure all imports appear before other statements. 🔧
group-exports Prefer named exports to be grouped together in a single export declaration
imports-first Replaced by import/first. 🔧
max-dependencies Enforce the maximum number of dependencies a module can have.
newline-after-import Enforce a newline after import statements. 🔧
no-anonymous-default-export Forbid anonymous values as default exports.
no-default-export Forbid default exports.
no-duplicates Forbid repeated import of the same module in multiple places. ☑️ 🚸 🔧
no-named-default Forbid named default exports.
no-named-export Forbid named exports.
no-namespace Forbid namespace (a.k.a. "wildcard" *) imports. 🔧
no-unassigned-import Forbid unassigned imports
order Enforce a convention in module import order. 🔧
prefer-default-export Prefer a default export if module exports a single name or multiple names.

eslint-plugin-import for enterprise

Available as part of the Tidelift Subscription.

The maintainers of eslint-plugin-import and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.

Installation

# inside your project's working tree
npm install eslint-plugin-import --save-dev

All rules are off by default. However, you may configure them manually in your .eslintrc.(yml|json|js), or extend one of the canned configs:

---
extends:
  - eslint:recommended
  - plugin:import/recommended
  # alternatively, 'recommended' is the combination of these two rule sets:
  - plugin:import/errors
  - plugin:import/warnings

# or configure manually:
plugins:
  - import

rules:
  import/no-unresolved: [2, {commonjs: true, amd: true}]
  import/named: 2
  import/namespace: 2
  import/default: 2
  import/export: 2
  # etc...

TypeScript

You may use the following snippet or assemble your own config using the granular settings described below it.

Make sure you have installed @typescript-eslint/parser and eslint-import-resolver-typescript which are used in the following configuration.

extends:
  - eslint:recommended
  - plugin:import/recommended
# the following lines do the trick
  - plugin:import/typescript
settings:
  import/resolver:
    # You will also need to install and configure the TypeScript resolver
    # See also https://github.com/import-js/eslint-import-resolver-typescript#configuration
    typescript: true
    node: true

Resolvers

With the advent of module bundlers and the current state of modules and module syntax specs, it's not always obvious where import x from 'module' should look to find the file behind module.

Up through v0.10ish, this plugin has directly used substack's resolve plugin, which implements Node's import behavior. This works pretty well in most cases.

However, webpack allows a number of things in import module source strings that Node does not, such as loaders (import 'file!./whatever') and a number of aliasing schemes, such as externals: mapping a module id to a global name at runtime (allowing some modules to be included more traditionally via script tags).

In the interest of supporting both of these, v0.11 introduces resolvers.

Currently Node and webpack resolution have been implemented, but the resolvers are just npm packages, so third party packages are supported (and encouraged!).

You can reference resolvers in several ways (in order of precedence):

  • as a conventional eslint-import-resolver name, like eslint-import-resolver-foo:
# .eslintrc.yml
settings:
  # uses 'eslint-import-resolver-foo':
  import/resolver: foo
// .eslintrc.js
module.exports = {
  settings: {
    'import/resolver': {
      foo: { someConfig: value }
    }
  }
}
  • with a full npm module name, like my-awesome-npm-module:
# .eslintrc.yml
settings:
  import/resolver: 'my-awesome-npm-module'
// .eslintrc.js
module.exports = {
  settings: {
    'import/resolver': {
      'my-awesome-npm-module': { someConfig: value }
    }
  }
}
  • with a filesystem path to resolver, defined in this example as a computed property name:
// .eslintrc.js
module.exports = {
  settings: {
    'import/resolver': {
      [path.resolve('../../../my-resolver')]: { someConfig: value }
    }
  }
}

Relative paths will be resolved relative to the source's nearest package.json or the process's current working directory if no package.json is found.

If you are interesting in writing a resolver, see the spec for more details.

Settings

You may set the following settings in your .eslintrc:

import/extensions

A list of file extensions that will be parsed as modules and inspected for exports.

This defaults to ['.js'], unless you are using the react shared config, in which case it is specified as ['.js', '.jsx']. Despite the default, if you are using TypeScript (without the plugin:import/typescript config described above) you must specify the new extensions (.ts, and also .tsx if using React).

"settings": {
  "import/extensions": [
    ".js",
    ".jsx"
  ]
}

If you require more granular extension definitions, you can use:

"settings": {
  "import/resolver": {
    "node": {
      "extensions": [
        ".js",
        ".jsx"
      ]
    }
  }
}

Note that this is different from (and likely a subset of) any import/resolver extensions settings, which may include .json, .coffee, etc. which will still factor into the no-unresolved rule.

Also, the following import/ignore patterns will overrule this list.

import/ignore

A list of regex strings that, if matched by a path, will not report the matching module if no exports are found. In practice, this means rules other than no-unresolved will not report on any imports with (absolute filesystem) paths matching this pattern.

no-unresolved has its own ignore setting.

settings:
  import/ignore:
    - \.coffee$          # fraught with parse errors
    - \.(scss|less|css)$ # can't parse unprocessed CSS modules, either

import/core-modules

An array of additional modules to consider as "core" modules--modules that should be considered resolved but have no path on the filesystem. Your resolver may already define some of these (for example, the Node resolver knows about fs and path), so you need not redefine those.

For example, Electron exposes an electron module:

import 'electron'  // without extra config, will be flagged as unresolved!

that would otherwise be unresolved. To avoid this, you may provide electron as a core module:

# .eslintrc.yml
settings:
  import/core-modules: [ electron ]

In Electron's specific case, there is a shared config named electron that specifies this for you.

Contribution of more such shared configs for other platforms are welcome!

import/external-module-folders

An array of folders. Resolved modules only from those folders will be considered as "external". By default - ["node_modules"]. Makes sense if you have configured your path or webpack to handle your internal paths differently and want to consider modules from some folders, for example bower_components or jspm_modules, as "external".

This option is also useful in a monorepo setup: list here all directories that contain monorepo's packages and they will be treated as external ones no matter which resolver is used.

If you are using yarn PnP as your package manager, add the .yarn folder and all your installed dependencies will be considered as external, instead of internal.

Each item in this array is either a folder's name, its subpath, or its absolute prefix path:

  • jspm_modules will match any file or folder named jspm_modules or which has a direct or non-direct parent named jspm_modules, e.g. /home/me/project/jspm_modules or /home/me/project/jspm_modules/some-pkg/index.js.

  • packages/core will match any path that contains these two segments, for example /home/me/project/packages/core/src/utils.js.

  • /home/me/project/packages will only match files and directories inside this directory, and the directory itself.

Please note that incomplete names are not allowed here so components won't match bower_components and packages/ui won't match packages/ui-utils (but will match packages/ui/utils).

import/parsers

A map from parsers to file extension arrays. If a file extension is matched, the dependency parser will require and use the map key as the parser instead of the configured ESLint parser. This is useful if you're inter-op-ing with TypeScript directly using webpack, for example:

# .eslintrc.yml
settings:
  import/parsers:
    "@typescript-eslint/parser": [ .ts, .tsx ]

In this case, @typescript-eslint/parser must be installed and require-able from the running eslint module's location (i.e., install it as a peer of ESLint).

This is currently only tested with @typescript-eslint/parser (and its predecessor, typescript-eslint-parser) but should theoretically work with any moderately ESTree-compliant parser.

It's difficult to say how well various plugin features will be supported, too, depending on how far down the rabbit hole goes. Submit an issue if you find strange behavior beyond here, but steel your heart against the likely outcome of closing with wontfix.

import/resolver

See resolvers.

import/cache

Settings for cache behavior. Memoization is used at various levels to avoid the copious amount of fs.statSync/module parse calls required to correctly report errors.

For normal eslint console runs, the cache lifetime is irrelevant, as we can strongly assume that files should not be changing during the lifetime of the linter process (and thus, the cache in memory)

For long-lasting processes, like eslint_d or eslint-loader, however, it's important that there be some notion of staleness.

If you never use eslint_d or eslint-loader, you may set the cache lifetime to Infinity and everything should be fine:

# .eslintrc.yml
settings:
  import/cache:
    lifetime: ∞  # or Infinity

Otherwise, set some integer, and cache entries will be evicted after that many seconds have elapsed:

# .eslintrc.yml
settings:
  import/cache:
    lifetime: 5  # 30 is the default

import/internal-regex

A regex for packages should be treated as internal. Useful when you are utilizing a monorepo setup or developing a set of packages that depend on each other.

By default, any package referenced from import/external-module-folders will be considered as "external", including packages in a monorepo like yarn workspace or lerna environment. If you want to mark these packages as "internal" this will be useful.

For example, if your packages in a monorepo are all in @scope, you can configure import/internal-regex like this

# .eslintrc.yml
settings:
  import/internal-regex: ^@scope/

SublimeLinter-eslint

SublimeLinter-eslint introduced a change to support .eslintignore files which altered the way file paths are passed to ESLint when linting during editing. This change sends a relative path instead of the absolute path to the file (as ESLint normally provides), which can make it impossible for this plugin to resolve dependencies on the filesystem.

This workaround should no longer be necessary with the release of ESLint 2.0, when .eslintignore will be updated to work more like a .gitignore, which should support proper ignoring of absolute paths via --stdin-filename.

In the meantime, see roadhump/SublimeLinter-eslint#58 for more details and discussion, but essentially, you may find you need to add the following SublimeLinter config to your Sublime project file:

{
    "folders":
    [
        {
            "path": "code"
        }
    ],
    "SublimeLinter":
    {
        "linters":
        {
            "eslint":
            {
                "chdir": "${project}/code"
            }
        }
    }
}

Note that ${project}/code matches the code provided at folders[0].path.

The purpose of the chdir setting, in this case, is to set the working directory from which ESLint is executed to be the same as the directory on which SublimeLinter-eslint bases the relative path it provides.

See the SublimeLinter docs on chdir for more information, in case this does not work with your project.

If you are not using .eslintignore, or don't have a Sublime project file, you can also do the following via a .sublimelinterrc file in some ancestor directory of your code:

{
  "linters": {
    "eslint": {
      "args": ["--stdin-filename", "@"]
    }
  }
}

I also found that I needed to set rc_search_limit to null, which removes the file hierarchy search limit when looking up the directory tree for .sublimelinterrc:

In Package Settings / SublimeLinter / User Settings:

{
  "user": {
    "rc_search_limit": null
  }
}

I believe this defaults to 3, so you may not need to alter it depending on your project folder max depth.

eslint-plugin-import's People

Contributors

arcanemagus avatar benmosher avatar bmish avatar bradzacher avatar byteme980 avatar christophercurrie avatar futpib avatar golopot avatar graingert avatar greenkeeperio-bot avatar j-f1 avatar jablko avatar jfmengels avatar josh avatar k15a avatar knpwrs avatar le0nik avatar ljharb avatar ljqx avatar lydell avatar manuth avatar millerized avatar rfermann avatar sheepsteak avatar singles avatar sompylasar avatar soryy708 avatar sosukesuzuki avatar tizmagik avatar yp avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

eslint-plugin-import's Issues

Allow configurable extensions

Hi,

Great plugin! We use React internally and use .jsx as our file extensions. Can you add an option to configure what extensions should be resolved? resolve already takes this option. In fact, maybe it would be best if we could pass an object of options which would be fed to resolve.

Thoughts?

nudge module.source.value report forward by 1 column

In the interest of highlighting the source string instead of its leading quote, as shown here:
screen shot 2015-09-10 at 11 45 11 am

...add 1 to the column location of node.source when reporting.

Probably want to pull this out to some util since it will be needed by a number of rules (no-duplicates shown here).

Also worth opening up PyCharm to see what the impact is there. This may be a Sublime quirk.

bring back interop

Upon reflection, things like Babel's different module modes (AMD, CommonJS, etc.) lend themselves to using ES6 imports for modules that may not be ES6 modules. (i.e., most npm modules)

Possible solutions:

  • setting for interop: detect CommonJS / AMD / UMD / System.js etc.
    • pro: can potentially do some rudimentary static analysis on exports
    • con: need to get it right/make assumptions based on the code
  • setting to ignore non-relative modules
    • pro: ignoring all node_modules is easy
    • con: not surgical; local files referenced with simple paths (i.e., symlink lib into node_modules) will be lost
  • magic comment to wrap non-ES6 imports
    • pro: easy to apply as the module implementer
    • con: noise in the source.
    • also: essentially just eslint-disable but scoped to the plugin (i.e., redundant)

working today: use //eslint-disable-line import/...

export default from '...'

verify this shows up as a default export in an importing module, i.e.

// mod.js
export default function () {}

// bar.js
export default from './mod'

// foo.js
import default from './bar' // <= should not report for import/default

Validate named exports

Ensure, given:

export * from './Panel'
export * from './buttons'

export { x as v } from './x'
  • ./Panel, ./buttons each have any named exports (import/export)
    • verify they fail silently if module is not resolved
  • ./Panel, ./buttons should be resolvable (import/no-unresolved)
  • import/named should confirm ./x exports name x

invalid: export { default as Glyphicon } from './Glyphicon'

Lee Byron's ES7 stage 1 proposed additions: (require babel-eslint for now)

// need default check
export v from 'mod'
export default from 'mod'

// need namespace check
export * as ns from 'mod'

// not sure if these will follow from the above
export v, {x, y as w} from "mod"
export v, * as ns from "mod"
  • validate mod has a default export (via import/default)
  • validate mod exposed any names (via import/namespace)
  • validate mod does not export a name v (via import/no-named-as-default)
  • update README with info about this ES7 support.

extra credit: something like an import/experimental setting for stage 0, 1, 2 for things like this? I figure it's implicitly on/off via import/parser=babel-eslint, by virtue of Espree probably barfing on this syntax, prompting a report from no-errors.

`no-assign`

New rule to report on assignment to any imported name (default, name, or namespace) at any scope.

Need to check:

  • namespace and namespace member assignment
  • specifier local name assignment (default and named)
  • look at function creation in addition to assignment expressions

`es6-only`

no-common => es6-only? or add no-amd?

no-common won't detect AMD modules... should the arms race of specific non-ES6 module types continue (more come to mind) or should it be retooled to report all import statements with specifiers* that point to a resolved module without ES6 syntax?

A thought: this would probably be cheaper to implement, as export syntax may only be present in the root scope. Would not need to traverse any deeper than the body, which means estraverse goes away and an empty ExportsMap is the harbinger of this report.

Also removes the need for "es6-only" as a setting for any rules.

I think I've sold myself on es6-only as a first-class rule, and dropping no-common + rule-specific measures.

  • note: this implicitly precludes imports such as import 'module'. Which makes sense.

import check breaks when exported objects contain spread

Here's a strange little edge case I just bumped into.

If any exported object contains a spread of another exported object, import/named and import/namespace breaks.

package.json dependencies:

"babel": "^5.8.23",
"babel-core": "^5.8.23",
"babel-eslint": "^4.1.1",
"eslint": "^1.3.1",
"eslint-plugin-import": "^0.7.8",
"eslint-plugin-react": "^3.3.1"

eslintrc:

{
  "parser": "babel-eslint",
  "plugins": [
    "react",
    "import"
  ],
  "env": {
    "browser": true,
    "node": true
  },
  "ecmaFeatures": {
    "arrowFunctions": true,
    "blockBindings": true,
    "classes": true,
    "defaultParams": true,
    "destructuring": true,
    "forOf": true,
    "generators": false,
    "modules": true,
    "objectLiteralComputedProperties": true,
    "objectLiteralDuplicateProperties": false,
    "objectLiteralShorthandMethods": true,
    "objectLiteralShorthandProperties": true,
    "spread": true,
    "superInFunctions": true,
    "templateStrings": true,
    "jsx": true
  }
}

test1.js contains:

export const test = {
    hello: '1'
};

export const betterTest = {
    ...test,
    world: '1'
};

test2.js contains:

import * as mock from './test1';
import {test} from './test1';

console.log(mock.betterTest);
console.log(test);

Running local ESLint:

`npm bin`/eslint --no-color test2.js

Outputs:

test2.js
  1:8   error  No exported names found in module './test1'        import/namespace
  2:9   error  test not found in './test1'                        import/named
  4:18  error  'betterTest' not found in imported namespace mock  import/namespace

✖ 3 problems (3 errors, 0 warnings)

CommonJS warning

Warning rule for ES6 imports where the remote module mentions module, module.exports, exports.

UMD not detected by `no-common`

Specifically, Immutable.js's UMD preamble does not trigger a no-common report:

function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  typeof define === 'function' && define.amd ? define(factory) :
  global.Immutable = factory()
}...

Import ordering

Are there any thoughts on implementing sorting rule? With logic like:

  • first "global" libraries should be imported
  • then local files (after \n\n)
  • everything should be sorted

Does it make any sense for anyone?

no-reassign rule fails

~/project/node_modules/eslint-plugin-import/lib/rules/no-reassign.js:15
    if (locals.has(id.name)) context.report(id, message(id.name))
                     ^
TypeError: Cannot read property 'name' of null
    at checkIdentifier (~/project/node_modules/eslint-plugin-import/lib/rules/no-reassign.js:15:22)
    at EventEmitter.FunctionDeclaration (~/project/node_modules/eslint-plugin-import/lib/rules/no-reassign.js:53:7)
    at EventEmitter.emit (events.js:129:20)
    at Controller.controller.traverse.enter (~/project/node_modules/eslint/lib/eslint.js:725:25)
    at Controller.__execute (~/project/node_modules/eslint/node_modules/estraverse/estraverse.js:393:31)
    at Controller.traverse (~/project/node_modules/eslint/node_modules/estraverse/estraverse.js:491:28)
    at EventEmitter.module.exports.api.verify (~/project/node_modules/eslint/lib/eslint.js:718:24)
    at verify (~/project/node_modules/gulp-eslint/index.js:21:25)
    at DestroyableTransform._transform (~/project/node_modules/gulp-eslint/index.js:44:18)
    at DestroyableTransform.Transform._read (~/project/node_modules/gulp-eslint/node_modules/through2/node_modules/readable-stream/lib/_stream_transform.js:184:10)

no-reassign flags wrong side of object destructuring

import { key } from './module'
const { key: path } = this.props.row

erronously flags key as a re-assign, while conversely

import { key } from './module'
const { path: key } = this.props.row

is not reported (but is the true re-assignment),

Swallow/log `getExports` exceptions

For example, I get this exception regarding an import of core Node module crypto:

Error: ENOENT, no such file or directory 'crypto'

I can only imagine the exceptions from trying to parse CoffeeScript... should just swallow errors as if the file does not exist, and let exists handle it.

Attempt to collect CommonJS exported names.

  • enable via import/commonjs or something. maybe even as a metaplugin?

at module scope level:

  • collect exports.[name] and exports["string literal"] as named exports
  • collect module.exports = { ... } as namespace (all keys as named exports)
  • collect module.exports = non-object as default
  • given none of those, warn on nothing (i.e., like being unresolved)

Things that will spuriously warn as a result:

  • exports defined in any non-module scope (i.e. in a closure)
  • namespaces defined as a return value from an IIFE or some such
  • default import of an object literal

test without babel polyfill

need to figure out how to run tests without the polyfill to simulate live plugin execution.

probably should compile tests or rewrite back to ES5, and reference lib/rules instead of src/rules.

no-reassign: destructuring

Ensure that it does not report on normal object/array creation, just Patterns for variable assignment/declaration/parameters.

`suggest-undef`

idea: check export cache for imported names that match undefined vars?

Failing to resolve paths.

Hi, presumably I'm doing something wrong here, but I couldn't find any info. I've just installed and added this plugin to my .eslintrc:

{
  "parser": "babel-eslint",
  "extends": "eslint:recommended",
  "plugins": [ "react", "import" ],
  "rules": {
    "comma-dangle": 0,
    "no-unused-vars": [2, {"vars": "all", "args": "none"}],
    "no-console": 1,
    "no-var": 2,
    "no-debugger": 1,
    "indent": [2, 2, {"SwitchCase": 1}],
    "max-len": [1, 80, 2],
    "prefer-const": 2
  },
  "settings": {
    "import/resolve": {
      "extenstions": [ ".es6", ".js", ".jsx" ]
    },
    "import/parser": "babel-eslint"
  },
  "env": {
    "browser": true
  }
}

But when I parse I get this:

/Users/rhys/Projects/2suggestions/paydirt/app/assets/javascripts/es6/components/projects/show_details.es6
  4:41  error    Unable to resolve path to module '../input/dropdown'        import/no-unresolved
  4:41  warning  'null' imported multiple times                              import/no-duplicates
  5:20  error    Unable to resolve path to module './status'                 import/no-unresolved
  5:20  warning  'null' imported multiple times                              import/no-duplicates
  6:18  error    Unable to resolve path to module '../icon'                  import/no-unresolved
  6:18  warning  'null' imported multiple times                              import/no-duplicates
  7:48  error    Unable to resolve path to module '../../entities/projects'  import/no-unresolved
  7:48  warning  'null' imported multiple times                              import/no-duplicates
  8:29  error    Unable to resolve path to module '../anchors'               import/no-unresolved
  8:29  warning  'null' imported multiple times                              import/no-duplicates
// show_details.es6

import Dropdown, { Item, Divider } from '../input/dropdown';
import Status from './status';
import Icon from '../icon';
import { hasHourly, invoiceUrl, moveUrl } from '../../entities/projects';
import { ModalAnchor } from '../anchors';

// ...

I'd really appreciate some help, this looks to be an excellent tool!

import/no-assignment

Looks like ESLint proper has updated no-redeclare to include modules as of 1.0.0-rc1 (see eslint/eslint#2948).

As such, should excise the redundant bits of no-reassign and refocus on imported namespace mutation.

no-duplicate-imports

(optional?) rule to warn on more than one import from the same module path, i.e.

import { x } from './mod'
import { y } from './mod'

reports on both lines, whereas

import { x, y } from './mod'

is valid.

Also need to consider an option / internal work up / an additional rule to consider the abbreviated export/import syntax from Lee Byron's ES7 import proposal.

i.e. no-import-export or something to warn on

import { foo } from './mod'
export { foo }

and recommend

export { foo } from './mod'

Those are valid ES6, but would need to consider things like

export MyCoolClass from './mod'

vs.

import MyCoolClass from './mod'
export default MyCoolClass

as the latter is the valid ES6 form.

babel-eslint parser option

Need to investigate swapping in babel-eslint as the parser instead of the baked-in espree, as an option.

For those brave enough to use babel-eslint, this would continue to allow all the bleeding-edge experimental JS through without parse errors. (prompted by issue #36)

Best case: infer this setting from the .eslintrc/rule context.
Worst case: add an import/parser setting analogously to the setting in ESLint proper.

Definition for rule 'import/no-reassign' was not found.

I'm getting an error using 0.7.4:

node_modules/eslint/lib/eslint.js:650
                    throw new Error("Definition for rule '" + key + "' was not
                          ^
Error: Definition for rule 'import/no-reassign' was not found.
    at node_modules/eslint/lib/eslint.js:650:27

babel-runtime

Question: use babel-runtime + runtime transformer instead of importing specific polyfills for Map, Set, etc.?

Could set as a peerDependency so installation is up to the user to determine necessity (wouldn't be required once Node fully implements all ES6 runtime features).

Error using eslint-plugin-import with SublimeText

I'm seeing an error in the SublimeText console when running 0.7.5:

SublimeLinter: eslint: Example.jsx ['node_modules/.bin/eslint', '--format', 'compact', '--stdin', '--stdin-filename', '__RELATIVE_TO_FOLDER__', '--stdin-filename', '@'] 
SublimeLinter: eslint output:
Error while loading rule 'import/export': Set is not defined
ReferenceError: Error while loading rule 'import/export': Set is not defined
    at exports.default (node_modules/eslint-plugin-import/lib/rules/export.js:16:22)
    at node_modules/eslint/lib/eslint.js:628:32
    at Array.forEach (native)
    at EventEmitter.module.exports.api.verify (node_modules/eslint/lib/eslint.js:619:16)
    at processText (node_modules/eslint/lib/cli-engine.js:201:27)
    at CLIEngine.executeOnText (node_modules/eslint/lib/cli-engine.js:361:26)
    at Object.cli.execute (node_modules/eslint/lib/cli.js:179:36)
    at configInit.initializeConfig.exitCode (node_modules/eslint/bin/eslint.js:13:28)
    at ConcatStream.<anonymous> (node_modules/eslint/node_modules/concat-stream/index.js:36:43)
    at ConcatStream.EventEmitter.emit (events.js:117:20) 

For reference, we use Set in nfl/react-helmet, and include a shim to polyfill them.

Export caching.

Investigate a plugin-level cache for export names, such that linting a large project in one go (one process) need not re-parse repeatedly imported modules.

Not even sure this is possible given the eslint architecture/plugin system. Feels intuitively useful, though.

Module resolution root path setting

Need a root path, a la webpack's resolve.root. i.e., if .eslintrc has something like

---
settings:
  resolve.root: 'src'

...then the resolver for resolve.js should look in path.join(process.cwd(), 'src') as an additional base path.

Extra credit: allow specification of a Node-compatible JS/JSON file with a path (i.e. './webpack.config.js:resolve.root').

May want to spec out some environment-based defaults (webpack, browserify, requirejs, explicitly check for node, etc.)

Need to investigate proper setting key conventions (i.e. import/resolveRoot?) within ESLint plugins.

[import/default] False positive when parsing a file using ES7.

When importing a module that contains stage 0 proposals, e.g.:

// Foo.jsx
class Foo {
    // ES7 static members
    static bar = true;
}

export default Foo;

// Importer.jsx
import Foo from "Foo"

I get the following false-positive:

error  No default export found in module  import/default

I dug into the code a bit and found Espree has issues parsing experimental code:

{ settings: 
   { 'import/ignore': [ 'node_modules' ],
     'import/resolve': { extensions: [Object], moduleDirectory: [Object] } },
  hasDefault: false,
  named: {},
  errors: 
   [ { [Error: Line 6: Unexpected token =]
       index: 185,
       lineNumber: 6,
       column: 24,
       description: 'Unexpected token =' } ] }

Note: We use babel-eslint in order to support linting with experimental code.

I'm not asking that you support experimental code (although it would be nice!), but it would be great if the parsing error was surfaced, or at the very least a note that this rule does not support experimental code.

no-named-as-default

Need a better name.

Given:

// foo.js
export default 'foo';
export const bar = 'baz';

...this would be valid:

import foo from './foo.js';

...and this would be reported:

import bar from './foo.js';

Message something like Using exported name 'bar' as identifier for default export.

Rationale: using an exported name as the name of the default export is either

  • misleading: others familiar with foo.js probably expect the name to be foo
  • a mistake: only needed to import bar and forgot the brackets (the case that is prompting this)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.