amatiasq / vsc-sort-imports

Sort ES6 imports automatically.
ISC License
58 stars 24 forks source link

TypeScript's `as const` causes `sort-imports` to fail. #43

Closed thisissami closed 5 years ago

thisissami commented 5 years ago

When trying to run sort-imports on the following:

import { PropertyTypes } from '$helpers/utilityTypes/PropertyTypes';
import { WeightUnits } from '$helpers/weight.lib';

export const componentTypes = {
  input: 'input',
  select: 'select',
  upload: 'upload'
} as const;

export type ComponentTypes = PropertyTypes<typeof componentTypes>;

vscode will display a message saying:

Error sorting imports: SyntaxError: Unexpected token, expected ";" (8:2)

Seems like sort-imports is unable to handle the valid as const; typescript.

amatiasq commented 5 years ago

You mean the feature added at Typescript 3.4?

That's reasonable, this tool uses Typescript 2.9. Support for 3.X would be good. PRs are welcome.

thisissami commented 5 years ago

@amatiasq that makes sense then. do you have any suggestions on where i'd need to tweak code? In looking at the codebase briefly, my sense is that I'll need to tweak something from the following, in src/sort.ts:

import importSort from 'import-sort';
...
export function sort(document: TextDocument): string {
    ...
    try {
        if (!useCache || !cachedParser) {
            const {
                parser,
                style,
                config: { options }
            } = getConfig(extension, directory, config);
            cachedParser = parser;
            cachedStyle = style;
            cachedOptions = options;
        }

        const result = importSort(
            currentText,
            cachedParser,
            cachedStyle,
            fileName,
            cachedOptions
        );
        return result.code;
    } catch (exception) {
        if (!getConfiguration<boolean>('suppress-warnings')) {
            window.showWarningMessage(`Error sorting imports: ${exception}`);
        }

        return null;
    }
}

either the import-sorts library will need to be updated, or the parser that is extracted from getConfig will need to be updated. Does that sound about right to you?

amatiasq commented 5 years ago

My bad, I forgot about the "parser" option.

Looks like import-sort-config@6 (the one we use) already supports import-sort-parser-typescript@6 which already has support for Typescript 3.x

That means you can enable typescript support by using Typescript parser.

"importSort": {
  ".ts, .tsx": {
    "parser": "typescript",
    "style": "eslint",
  }
}

There is a bug I found: parser.parseImports is not a function. It's solved by installing the typescript parser manually:

npm i -D import-sort-parser-typescript