willhoney7 / eslint-plugin-import-helpers

ESLint plugin to help enforce a configurable order for import statements
288 stars 17 forks source link

Different groups for node_modules and internal modules #30

Closed jefferson-vieira closed 4 years ago

jefferson-vieira commented 4 years ago

I wondered if there was a way to separate imports from node_modules from other internal imports Is common (and useful) for devs map internal src files in jsconfig.json or tsconfig.json, like baseUrl and paths

.
+-- node_modules
|   +-- express
+-- src
|   +-- controllers
|   |   +-- MainController.js
|   +-- app.js
|   +-- index.js
+-- .eslintrc.json
+-- jsconfig.json
// jsconfig.json

{
    "compilerOptions": {
        "baseUrl": "./src",
        "paths": { "*": ["*"] }
    }
}
// .eslintrc.json

{
    "plugins": ["eslint-plugin-import-helpers"],
    "rules": {
        "import-helpers/order-imports": [
            "error",
            {
                "newlinesBetween": "always",
                "groups": [
                    "node-module", // old "module", but dedicated for project dependencies (package.json)
                    "module", // new using for "module", dedicated for nom-project dependencies
                    ["parent", "sibling", "index"]
                ],
                "alphabetize": { "order": "asc", "ignoreCase": true }
            }
        ]
    }
}
// index.js

import express from 'express';

import MainController from 'controllers/MainController'

import app from './app'

This a simple example... but please consider a deep folder structure that benefit a relative import method

willhoney7 commented 4 years ago

Honestly, I think using a regexp group gets you 99% there. Use module for npm modules, then for known internal paths (baseUrl), add them as regexp.

{
    "newlinesBetween": "always",
    "groups": [
        "module",
        ["/^controllers/", "/^utils/"], // here
        ["parent", "sibling", "index"]
    ],
    "alphabetize": { "order": "asc", "ignoreCase": true }
}

I'm pretty wary of adding new groups since the regexp can handle almost everything.

willhoney7 commented 4 years ago

closing...