IanVS / prettier-plugin-sort-imports

An opinionated but flexible prettier plugin to sort import statements
Apache License 2.0
892 stars 21 forks source link

Support for conditional imports / Allow to ignore conditional paths #168

Closed Neiz-Kap closed 1 month ago

Neiz-Kap commented 2 months ago

Is your feature request related to a problem? I'm working on enabling absolute imports for my job project on TypeScript and NodeJS (Express). I'm using module-alias package to allow them to be worked in compiled js code and I noticed, that integrated entry of the package breaks running the project in dev mode, but it works well in build one.

I came up with the idea to switch off the package import for not production node environment by if block In other hand, I use your plugin to sort imports, because we decided to rework our approach for imports (to keep them sorted, readable, also keep a balance between relative and absolute paths and have couple eslint rules for them)

So I have follow code:

// prettier-ignore
/* eslint-disable import/first */
import envConfig from './configs/config'

// prettier-ignore
if (envConfig.nodeEnv === 'production') {
 // prettier-ignore
  require('@google-cloud/trace-agent').start()
  require('module-alias/register')
}

import { createApp } from './app'
import { initializeMongoose } from './configs/db/mongoose'
import { InternalServerError } from './modules/errors/model/app-errors'

My requirements

Describe the solution you'd like There are follow-up versions:

Describe alternatives you've considered

Additional context

Here's my prettier configuration:

{
  "semi": false,
  "trailingComma": "all",
  "singleQuote": true,
  "printWidth": 120,
  "tabWidth": 2,
  "plugins": [
    "@ianvs/prettier-plugin-sort-imports"
  ],
  "importOrder": [
    "<THIRD_PARTY_MODULES>",
    "",
    "^@(?!/)",
    "",
    "^@/",
    "",
    "^[./]"
  ],
  "importOrderSeparation": true,
  "importOrderSortSpecifiers": true
}
IanVS commented 2 months ago

Hi, thanks for the issue. If I understand correctly, you want to mix require statements into your import statements, and keep them sorted that way. The problem is that import statements are always evaluated before anything else, so even if you have require statements mixed together, they won't run in that order, which is confusing. That's why we pull all import statements up to the top of the file, to reflect the order in which they will be evaluated.

Instead of using dynamic imports like this, have you considered using conditional subpath imports? https://nodejs.org/api/packages.html#subpath-imports. You might be able to achieve the same thing you're looking for without the use of an additional alias dependency.