0
# Import Processing
1
2
Core preprocessing functionality that analyzes and sorts import statements according to configured patterns using Babel AST processing.
3
4
## Main Preprocessor Functions
5
6
### preprocessor
7
8
Core preprocessing logic that sorts imports according to configuration options.
9
10
```typescript { .api }
11
function preprocessor(code: string, options: PrettierOptions): string
12
```
13
14
**Parameters:**
15
- `code`: Source code string to process
16
- `options`: Prettier options including plugin configuration
17
18
**Returns:** Processed code string with sorted imports
19
20
The core preprocessing function that:
21
22
1. Parses code using Babel parser with configured plugins
23
2. Extracts import declarations and directives from AST
24
3. Applies configured sorting and grouping rules
25
4. Generates formatted code with sorted imports
26
27
#### Usage Example
28
29
```typescript
30
import { preprocessor } from '@trivago/prettier-plugin-sort-imports';
31
32
const sortedCode = preprocessor(sourceCode, {
33
importOrder: ["^@core/(.*)$", "^[./]"],
34
importOrderSeparation: true,
35
importOrderSortSpecifiers: true,
36
// ... other Prettier options
37
});
38
```
39
40
### defaultPreprocessor
41
42
Default preprocessor that handles most file types while skipping Vue and Svelte files.
43
44
```typescript { .api }
45
function defaultPreprocessor(code: string, options: PrettierOptions): string
46
```
47
48
**Parameters:**
49
- `code`: Source code string to process
50
- `options`: Prettier options including filepath information
51
52
**Returns:** Processed code string or original code for Vue/Svelte files
53
54
Conditional preprocessor that:
55
- Returns original code unchanged for `.svelte` and `.vue` files
56
- Calls main `preprocessor` function for all other file types
57
58
This allows framework-specific preprocessors to handle their respective file types.
59
60
## Processing Pipeline
61
62
### AST Extraction
63
64
The preprocessor uses Babel to parse source code and extract relevant nodes:
65
66
```typescript { .api }
67
interface ASTExtractionResult {
68
importNodes: ImportDeclaration[];
69
directives: Directive[];
70
}
71
72
function extractASTNodes(ast: Program): ASTExtractionResult
73
```
74
75
Extracts import declarations and directives (like "use strict") from the parsed AST while preserving their original positions and comments.
76
77
### Import Sorting
78
79
Core sorting logic that groups and orders imports according to configuration:
80
81
```typescript { .api }
82
type GetSortedNodes = (
83
nodes: ImportDeclaration[],
84
options: Pick<
85
PrettierOptions,
86
| 'importOrder'
87
| 'importOrderCaseInsensitive'
88
| 'importOrderSeparation'
89
| 'importOrderGroupNamespaceSpecifiers'
90
| 'importOrderSortSpecifiers'
91
| 'importOrderSideEffects'
92
>
93
) => ImportOrLine[]
94
95
function getSortedNodes(
96
importNodes: ImportDeclaration[],
97
options: SortingOptions
98
): ImportOrLine[]
99
```
100
101
**Processing Steps:**
102
103
1. **Group Matching**: Matches imports against `importOrder` patterns
104
2. **Third-party Handling**: Identifies and positions unmatched imports
105
3. **Specifier Sorting**: Sorts named imports if enabled
106
4. **Namespace Grouping**: Groups namespace imports if enabled
107
5. **Separation**: Adds newline nodes between groups if enabled
108
109
### Code Generation
110
111
Final step that generates formatted code from sorted AST nodes:
112
113
```typescript { .api }
114
function getCodeFromAst(
115
nodes: Statement[],
116
directives: Directive[],
117
originalCode: string,
118
interpreter?: InterpreterDirective | null,
119
options?: Pick<PrettierOptions, 'importOrderImportAttributesKeyword'>
120
): string
121
```
122
123
**Parameters:**
124
- `nodes`: AST statement nodes including imports and newline separators
125
- `directives`: Preserved directives from original code
126
- `originalCode`: Original source code for fallback
127
- `interpreter`: Shebang or interpreter directive
128
- `options`: Code generation options
129
130
**Returns:** Final formatted code string
131
132
## Utility Functions
133
134
### Parser Plugin Processing
135
136
```typescript { .api }
137
function getExperimentalParserPlugins(
138
importOrderParserPlugins?: ImportOrderParserPlugin[]
139
): ParserPlugin[]
140
```
141
142
Processes plugin configuration and returns Babel parser plugins, handling both simple plugin names and plugins with options.
143
144
### Sort Ignore Detection
145
146
```typescript { .api }
147
function isSortImportsIgnored(importNodes: ImportDeclaration[]): boolean
148
```
149
150
Checks if import sorting should be skipped based on the presence of `// sort-imports-ignore` comments.
151
152
### Comment Adjustment
153
154
```typescript { .api }
155
function adjustCommentsOnSortedNodes(
156
sortedNodes: ImportOrLine[],
157
originalNodes: ImportDeclaration[],
158
sourceCode: string
159
): ImportOrLine[]
160
```
161
162
Preserves and repositions comments associated with import statements after sorting to maintain code documentation.
163
164
### Import Specifier Sorting
165
166
```typescript { .api }
167
function getSortedImportSpecifiers(
168
importDeclaration: ImportDeclaration,
169
options: Pick<PrettierOptions, 'importOrderSortSpecifiers'>
170
): ImportDeclaration
171
```
172
173
Sorts named imports within individual import statements when `importOrderSortSpecifiers` is enabled.
174
175
### Import Node Extraction
176
177
```typescript { .api }
178
function getImportNodes(code: string, options?: ParserOptions): ImportDeclaration[]
179
```
180
181
**Parameters:**
182
- `code`: Source code string to parse
183
- `options`: Optional Babel parser configuration options
184
185
**Returns:** Array of import declaration AST nodes
186
187
Parses source code and extracts all import declarations, excluding imports inside TypeScript module declarations. Useful for custom import processing outside the main plugin workflow.
188
189
#### Usage Example
190
191
```typescript
192
import { getImportNodes } from '@trivago/prettier-plugin-sort-imports';
193
194
const importNodes = getImportNodes(sourceCode, {
195
plugins: ['typescript', 'jsx']
196
});
197
```
198
199
### Node Removal Utility
200
201
```typescript { .api }
202
function removeNodesFromOriginalCode(
203
code: string,
204
nodes: (Statement | CommentBlock | Directive | CommentLine | ImportDeclaration | InterpreterDirective)[]
205
): string
206
```
207
208
**Parameters:**
209
- `code`: Original source code string
210
- `nodes`: Array of AST nodes to remove from the code
211
212
**Returns:** Modified code string with specified nodes removed
213
214
Removes specified AST nodes from the original source code by matching their text content. Used internally for clean code generation but can be useful for custom preprocessing.
215
216
### Natural Sorting Utility
217
218
```typescript { .api }
219
export { naturalSort };
220
```
221
222
Re-exported natural sorting function from the `javascript-natural-sort` library, used internally for import sorting but available for custom sorting needs.
223
224
## Processing Constants
225
226
### Special Keywords
227
228
```typescript { .api }
229
const THIRD_PARTY_MODULES_SPECIAL_WORD = '<THIRD_PARTY_MODULES>';
230
const THIRD_PARTY_TYPES_SPECIAL_WORD = '<THIRD_PARTY_TS_TYPES>';
231
const TYPES_SPECIAL_WORD = '<TS_TYPES>';
232
```
233
234
Special placeholder strings used in `importOrder` configuration to control positioning of automatically detected import groups.
235
236
### Parser Plugin Constants
237
238
```typescript { .api }
239
const flow: ParserPlugin = 'flow';
240
const typescript: ParserPlugin = 'typescript';
241
const jsx: ParserPlugin = 'jsx';
242
```
243
244
Predefined parser plugin constants for common Babel plugins used in import processing.
245
246
### Node Type Identifiers
247
248
```typescript { .api }
249
const chunkSideEffectNode = 'side-effect-node';
250
const chunkSideOtherNode = 'other-node';
251
```
252
253
Constants used internally to categorize different types of import nodes during processing.
254
255
### Formatting Constants
256
257
```typescript { .api }
258
const newLineCharacters = '\n\n';
259
const sortImportsIgnoredComment = 'sort-imports-ignore';
260
261
const newLineNode: ExpressionStatement;
262
```
263
264
Constants for consistent formatting and special comment detection. The `newLineNode` is an AST node representing blank line separators between import groups.
265
266
## Error Handling
267
268
The preprocessor includes comprehensive error handling and safety mechanisms:
269
270
### Framework Dependency Fallbacks
271
272
**Svelte Parser Loading**:
273
```typescript { .api }
274
function createSvelteParsers(): { parsers?: any } | {}
275
```
276
277
Gracefully handles missing Svelte dependencies:
278
```typescript
279
try {
280
var { parsers } = require('prettier-plugin-svelte');
281
} catch {
282
return {}; // Returns empty object if plugin unavailable
283
}
284
```
285
286
### Parser Plugin Configuration Errors
287
288
**JSON Parsing Safety**:
289
```typescript { .api }
290
function getExperimentalParserPlugins(
291
importOrderParserPlugins: string[]
292
): ParserPlugin[]
293
```
294
295
Validates plugin configuration with detailed error messages:
296
```typescript
297
try {
298
plugin = JSON.parse(pluginNameOrJson) as ParserPluginWithOptions;
299
} catch (e) {
300
throw Error('Invalid JSON in importOrderParserPlugins: ' + pluginNameOrJson);
301
}
302
```
303
304
### Processing Safety Mechanisms
305
306
- **Empty Import Check**: Returns original code unchanged if no imports are found
307
- **Ignore Comment Check**: Skips processing when `// sort-imports-ignore` comment is present
308
- **TypeScript Module Exclusion**: Safely excludes imports inside TypeScript module declarations
309
- **Parser Error Handling**: Falls back to original code on Babel parse errors
310
- **AST Generation Safety**: Preserves original structure on code generation failures
311
312
### Framework-Specific Error Handling
313
314
- **Missing Vue Dependencies**: Graceful fallback when `@vue/compiler-sfc` unavailable
315
- **Missing Svelte Dependencies**: Graceful fallback when `prettier-plugin-svelte` unavailable
316
- **Invalid SFC Structure**: Handle malformed Vue or Svelte component files safely
317
- **Framework Parse Errors**: Preserve original code on framework-specific parse failures
318
319
### Configuration Validation
320
321
- **Invalid RegExp Patterns**: Reports clear errors for malformed `importOrder` patterns
322
- **Plugin Option Validation**: Validates JSON strings in parser plugin configurations
323
- **Type Safety**: Comprehensive TypeScript typing prevents configuration mismatches
324
325
## Integration with Prettier
326
327
The preprocessor integrates seamlessly with Prettier's pipeline:
328
329
1. **Parser Registration**: Extends existing Prettier parsers
330
2. **Option Integration**: Uses Prettier's option system
331
3. **File Type Handling**: Respects Prettier's file type detection
332
4. **Source Map Preservation**: Maintains debugging information where possible