Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

import-order: Relative imports now listed first when using Yarn 2 PnP #2164

Closed
ryb73 opened this issue Jul 22, 2021 · 7 comments
Closed

import-order: Relative imports now listed first when using Yarn 2 PnP #2164

ryb73 opened this issue Jul 22, 2021 · 7 comments

Comments

@ryb73
Copy link

ryb73 commented Jul 22, 2021

Minimal reproduction: https://github.com/ryb73/eslint-import-order-repro

I have the following imports:

import { blah } from "./blah";
import { version } from "typescript";
import { blah2 } from "./blah2";

With .eslintrc.js:

"use strict";

module.exports = {
  env: {
    es6: true,
    browser: true,
  },

  ignorePatterns: [`.pnp.js`, `.yarn`, `lib`, `.vscode`],

  overrides: [
    {
      files: [`./.eslintrc.js`],
      parserOptions: {
        sourceType: `script`,
      },
    },
  ],

  parserOptions: {
    sourceType: `module`,
  },

  plugins: [`import`],

  rules: {
    "import/order": [`warn`,
      {
        alphabetize: { order: `asc`, caseInsensitive: true },
        "newlines-between": `never`,
      },
    ],
  },

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

I expect to get the following warning:

  2:1  warning  `typescript` import should occur before import of `./blah`  import/order

Instead I get:

  3:1  warning  `./blah2` import should occur before import of `typescript`  import/order

It appears to happen when using Yarn 2's PNP linker.

@ljharb
Copy link
Member

ljharb commented Jul 23, 2021

This sounds unsurprising, since pnp probably resolves everything to the same kind of file. @arcanis?

It’s possible that when using pnp, a custom import resolver will be needed, since it’s not using node resolution.

@younho9
Copy link

younho9 commented Aug 21, 2021

I just listed external modules in pathGroups, though cumbersome, to make them recognized as external modules.

...
rules: {
  'import/order': [
    'warn',
    {
      'newlines-between': 'always',
      'pathGroups': [
        {
          pattern: 'react',
          group: 'external',
        },
        {
          pattern: 'react-dom',
          group: 'external',
        },
      ],
      'alphabetize': {
        order: 'asc',
        caseInsensitive: true,
      },
    },
  ],
},
...

@a-tonchev
Copy link

I have the same bug!

    "import/order": ["error", {
      "newlines-between": "always",
      "groups": [["builtin", "external"], "internal", ["parent", "sibling", "index"]],
      "pathGroups": [
        {
          "pattern": "@/",
          "group": "internal",
          "position": "after"
        }
      ]
    }]

sibling imports are placed above my "internal" group.

With version 2.23.4, there is no problem! For now a workaround is to downgrade to this version.

younho9 added a commit to younho9/lib that referenced this issue Sep 11, 2021
* docs: add github issue and pr template

* add `.github/ISSUE_TEMPLATE/feature-request.md`

* add `.github/pull_request_template.md`

Refs: https://github.com/younho9/dotfiles/tree/main/.github

* chore: yarn workspace init

* chore: setup commitlint

* commitlint 설정

* husky 설정

Refs:
- https://github.com/conventional-changelog/commitlint#getting-started
- https://typicode.github.io/husky

* chore: setup prettier

* chore: setup eslint

* chore(`eslint`): modify eslint-plugin-import rules

- `import/no-unresolved` 활성화
- `import/order`
  - 에러 레벨 `warn`으로 낮춤
  - `pathGroupsExcludedImportTypes` 옵션 제거 (해당 옵션 이해하지 못함)
  - PnP mode에서, 외부 모듈이 제대로 정렬되지 않는 이슈 있음
    - `pathGroups`에 외부 모듈을 직접 나열하면 해결 가능

See:
- import-js/eslint-plugin-import#2164

* docs(`.github`): update issue templates

* chore: setup babel build process for modules

* chore: setup babel build process

See:
- https://krasimirtsonev.com/blog/article/transpile-to-esm-with-babel
- https://ui.toast.com/weekly-pick/ko_20180716

* chore: add license

* chore: modify monorepo setup

- Update .gitignore
- Add .gitattributes
- Add dist and tsconfig.json of root to .prettierignore
- Add yarn berry workspace-tool plugin

* feat(`prettier-config`): add prettier config

* feat(`prettier-config`): change to module.exports

* feat(`prettier-config`): modify babel config

* chore: add prettier-config to root dev deps

* chore(`release`): change git commit message

* chore: install prettier config

* chore(`prettier-config`): add build cycle

* chore(`monorepo`): change name and add version & repo

* chore(`lerna`): configure changelog preset
@dlindenkreuz
Copy link

After editing the eslint plugin settings, I don't see this error anymore with Yarn v3.1.1 and eslint-plugin-import@2.25.4.

Important (from the README):

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.

When adding .yarn to the import/external-module-folders setting, the error disappeared.

@a-tonchev
Copy link

a-tonchev commented Mar 23, 2022

For me the fix was

  1. to change the pattern from @/ to @/**
  2. and to remove the position: 'after'

Basically:

    "import/order": ["error", {
      "newlines-between": "always",
      "groups": [["builtin", "external"], "internal", ["parent", "sibling", "index"]],
      "pathGroups": [
        {
          "pattern": "@/**",
          "group": "internal"
        }
      ]
    }]

    ```
    
 This works with the newest versions well.

@ljharb ljharb closed this as completed Mar 23, 2022
@saengmotmi
Copy link

saengmotmi commented Nov 5, 2022

in my case, it works for me

// .eslintrc.js
const getExternals = () => {
  const getPackageJson = () =>
    require(path.resolve(process.cwd(), 'package.json'));

  const { dependencies, peerDependencies, devDependencies } = getPackageJson();

  return Object.keys({
    ...dependencies,
    ...peerDependencies,
    ...devDependencies,
  });
};

// ...
    'import/order': [
      'error',
      {
        groups: [
          ['builtin', 'external'],
          ['internal', 'parent', 'sibling'],
        ],
        pathGroups: [
          ...getExternals().map((name) => ({
            pattern: `${name}`,
            group: 'external',
          })),
          ...getExternals().map((name) => ({
            pattern: `${name}/**`,
            group: 'external',
          })),
// ...

@saengmotmi
Copy link

maybe this is more proper way to sort external deps

// .eslintrc.js
// ...
  settings: {
    'import/external-module-folders': ['.yarn'],
// ...

thx @dlindenkreuz :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

6 participants