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

support absolute path imports as local imports (ts/jsconfig.json) #162

Open
1 task
ramykl opened this issue Jul 29, 2022 · 5 comments
Open
1 task

support absolute path imports as local imports (ts/jsconfig.json) #162

ramykl opened this issue Jul 29, 2022 · 5 comments

Comments

@ramykl
Copy link

ramykl commented Jul 29, 2022

Your Environment

  • Prettier version: 2.1.1
  • node version [v16.16.0]:
  • package manager: [npm@8]
  • IDE: [IntelliJ IDEA]

Describe the bug

When using a jsconfig.json or tsconfig.json file to allow absolute path imports, these are treated as third party imports and no longer grouped with local imports. Theses are clearly local imports so should not be grouped in the 3 party section

To Reproduce

  • create new project with CRA (this now creates a jsconfig.json file)
  • create some folders and subfiles inside of src folder
  • import those files using a mix of absolute path, relative path and 3rd party packages in a file
  • run prettier

Expected behavior

the imported files would be sorted in order with:

  1. Third party packages
  2. absolute path
  3. relative
    (2 and 3 may be combined)

Screenshots, code sample, etc

example folder structure:

  • node_modules
  • src
    • components
      • button.js
    • routes
      • page.js
    • utils
      • helper.js
    • app.js
    • index.js
  • package.json
  • jsconfig.json

jsconfig.json

{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "include": ["src"]
}

page.js

import react from 'react'

import Button from 'components/button'
import helper from 'utils/helper'
....


// When I run prettier this will rearrange the imports to 
import Button from 'components/button'
import react from 'react'
import helper from 'utils/helper'
...

Theses are clearly local imports so should not be grouped in the 3 party section

Configuration File (cat .prettierrc, prettier.config.js, .prettier.js)

.prettierrc

{
  "singleQuote": true,
  "trailingComma": "es5",
  "tabWidth": 2,
  "printWidth": 100,
  "useTabs": false,
  "semi": true,
  "quoteProps": "as-needed",
  "jsxSingleQuote": false,
  "bracketSpacing": true,
  "jsxBracketSameLine": false,
  "arrowParens": "always",
  "importOrder": [
    "^[./]"
  ],
  "importOrderSeparation": true,
  "importOrderSortSpecifiers": true
}

Contribute to @trivago/prettier-plugin-sort-imports

  • I'm willing to fix this bug 🥇
@tearf001
Copy link

tearf001 commented Sep 30, 2022

Could this help?
.prettierrc.js of mine

const packages = require('./package.json').dependencies;
const sortedPackages = Object.keys(packages).sort();
module.exports = {
  printWidth: 120,
  tabWidth: 2,
  useTabs: false,
  semi: true,
  singleQuote: true,
  trailingComma: 'all',
  arrowParens: 'avoid',
  endOfLine: 'lf',
  // any order specification. for example. styles last   \./\S+\.\w+ss
  importOrder: sortedPackages.concat(['<THIRD_PARTY_MODULES>', '^\\.\\./', '^\\./']),
  importOrderSeparation: true,
  importOrderSortSpecifiers: true,
  importOrderCaseInsensitive: true,
};

Actually <THIRD_PARTY_MODULES> act as your custom imports!

@curtvict
Copy link

curtvict commented Oct 4, 2022

Thanks for the inspo, @tearf001!

Since I didn't want importOrderSeparation to add a space between every 3rd party dependency, I went with:

const { readdirSync } = require('fs');

const { baseUrl } = require('./tsconfig.json').compilerOptions;
const baseUrlSubdirectories = readdirSync(`${__dirname}/${baseUrl}`, { withFileTypes: true })
  .filter((entry) => entry.isDirectory())
  .map((entry) => entry.name);

const baseUrlSubdirectoryRegex = `^(${baseUrlSubdirectories.join('|')})`;

module.exports = {
  $schema: 'http://json.schemastore.org/prettierrc',
  arrowParens: 'always',
  bracketSpacing: true,
  bracketSameLine: false,
  jsxSingleQuote: false,
  printWidth: 100,
  proseWrap: 'always',
  quoteProps: 'as-needed',
  semi: true,
  singleQuote: true,
  tabWidth: 2,
  trailingComma: 'es5',
  useTabs: false,
  importOrder: [baseUrlSubdirectoryRegex, '^.?[./]'],
  importOrderSeparation: true,
};

This will group any import listed as a dependency or devDependency (test imports is what I'm thinking here) at the top of the file, followed by another group of all of my "absoluteish" imports (as dictated by my tsconfig's baseUrl directory), followed by any relative (./blah or ../blah/blah) imports.

@Cordobo
Copy link

Cordobo commented Dec 19, 2022

Thanks @curtvict for sharing your solution, it works like a charm. As our code has some files at the baseUrl-level, e.g. src/config.ts which are imported like import { PORT } from 'config', we also included files via || entry.isFile()and replaced the file extension, in our case .ts.

Complete prettierrc.js file:

const { readdirSync } = require('node:fs')
const { baseUrl } = require('./tsconfig.json').compilerOptions

const baseUrlSubdirectories = readdirSync(`${__dirname}/${baseUrl}`, { withFileTypes: true })
  .filter((entry) => entry.isDirectory() || entry.isFile())
  .map((entry) => entry.name.replace('.ts', ''))
const baseUrlSubdirectoryRegex = `^(${baseUrlSubdirectories.join('|')})`

module.exports = {
  arrowParens: 'always',
  bracketSameLine: false,
  bracketSpacing: true,
  printWidth: 120,
  semi: false,
  singleQuote: true,
  trailingComma: 'es5',
  importOrder: ['<THIRD_PARTY_MODULES>', baseUrlSubdirectoryRegex, '^[./]'],
  importOrderSeparation: true,
  importOrderSortSpecifiers: true,
  importOrderParserPlugins: ['typescript', 'decorators-legacy'],
}

or even shorter (we went with the more explicit version above)

const baseUrlSubdirectories = readdirSync(`${__dirname}/${baseUrl}`, { withFileTypes: false })
  .map((entry) => entry.replace('.ts', ''))
const baseUrlSubdirectoryRegex = `^(${baseUrlSubdirectories.join('|')})`

@amiroous
Copy link

This doesn't solve for other formats like YAML and JSON.
There should be a real fix to handle this bug

@aronfiechter
Copy link

The above solutions are not working for us, our local imports are treated as if they were third party imports and put in that group instead of the bottom.

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

No branches or pull requests

6 participants