0
# Build System
1
2
Comprehensive compilation system for Vue Single File Components, TypeScript, and CSS with multi-format output support. The build system handles the complete transformation pipeline from source Vue components to production-ready library packages.
3
4
**⚠️ Important Note**: The functions documented below are internal implementation details and are NOT exported from the main @vant/cli package. They cannot be imported and used programmatically. The documentation is provided for understanding the build system's internal architecture.
5
6
## Capabilities
7
8
### Vue SFC Compilation
9
10
Compilation of Vue Single File Components into separate JavaScript, CSS, and TypeScript declaration files.
11
12
```typescript { .api }
13
/**
14
* Vue SFC descriptor containing parsed template, script, and styles
15
*/
16
interface SFCDescriptor {
17
template?: {
18
content: string;
19
attrs: Record<string, string | true>;
20
};
21
script?: {
22
content: string;
23
attrs: Record<string, string | true>;
24
};
25
scriptSetup?: {
26
content: string;
27
attrs: Record<string, string | true>;
28
};
29
styles: Array<{
30
content: string;
31
attrs: Record<string, string | true>;
32
}>;
33
}
34
35
/**
36
* Parses Vue Single File Component into descriptor object
37
* @param filename - Path to .vue file
38
* @returns SFC descriptor with parsed sections
39
*/
40
function parseSfc(filename: string): SFCDescriptor;
41
42
/**
43
* Compiles Vue SFC to separate JavaScript and CSS files
44
* Handles template compilation, script processing, and style extraction
45
* @param filePath - Path to .vue file to compile
46
* @returns Promise that resolves when compilation is complete
47
*/
48
function compileSfc(filePath: string): Promise<any>;
49
```
50
51
**Usage:**
52
```typescript
53
import { parseSfc, compileSfc } from "@vant/cli";
54
55
// Parse SFC structure
56
const descriptor = parseSfc('./src/button/index.vue');
57
console.log(descriptor.template?.content);
58
console.log(descriptor.script?.content);
59
60
// Compile SFC to output files
61
await compileSfc('./src/button/index.vue');
62
// Generates: button/index.js, button/index.css, button/index.d.ts
63
```
64
65
### Style Compilation
66
67
Compilation of CSS, Less, and Sass files with preprocessing support.
68
69
```typescript { .api }
70
/**
71
* Compiles style files (CSS, Less, Sass) to CSS output
72
* Handles preprocessing, autoprefixing, and optimization
73
* @param filePath - Path to style file to compile
74
* @returns Promise that resolves when compilation is complete
75
*/
76
function compileStyle(filePath: string): Promise<void>;
77
78
/**
79
* Current CSS preprocessor language detected from configuration
80
*/
81
type CSS_LANG = 'css' | 'less' | 'scss';
82
83
/**
84
* Gets the base CSS file path for the project
85
* @returns Path to base CSS file or null if not found
86
*/
87
function getCssBaseFile(): string | null;
88
89
/**
90
* Replaces CSS import extensions in code for compatibility
91
* @param code - Source code containing CSS imports
92
* @returns Code with updated CSS import extensions
93
*/
94
function replaceCSSImportExt(code: string): string;
95
```
96
97
**Usage:**
98
```typescript
99
import { compileStyle, getCssBaseFile } from "@vant/cli";
100
101
// Compile individual style file
102
await compileStyle('./src/button/index.less');
103
104
// Get base styles
105
const baseFile = getCssBaseFile();
106
if (baseFile) {
107
console.log(`Base styles: ${baseFile}`);
108
}
109
```
110
111
### Bundle Generation
112
113
Creation of library bundles in multiple formats using Vite.
114
115
```typescript { .api }
116
/**
117
* Bundle configuration options
118
*/
119
interface BundleOption {
120
/** Enable minification for production builds */
121
minify?: boolean;
122
/** Output formats to generate (es, cjs, umd, etc.) */
123
formats: LibraryFormats[];
124
/** External dependencies to exclude from bundle */
125
external?: string[];
126
}
127
128
/**
129
* Compiles library bundles using Vite
130
* Generates multiple format outputs based on configuration
131
* @returns Promise that resolves when bundle compilation is complete
132
*/
133
function compileBundles(): Promise<void>;
134
135
/**
136
* Generates Vite configuration for package builds
137
* @param options - Bundle configuration options
138
* @returns Vite InlineConfig for package building
139
*/
140
function getViteConfigForPackage(options: BundleOption): InlineConfig;
141
```
142
143
**Usage:**
144
```typescript
145
import { compileBundles, getViteConfigForPackage } from "@vant/cli";
146
147
// Generate bundles with default configuration
148
await compileBundles();
149
150
// Custom Vite configuration
151
const viteConfig = getViteConfigForPackage({
152
minify: true,
153
formats: ['es', 'cjs'],
154
external: ['vue']
155
});
156
```
157
158
### Package Style Generation
159
160
Generation of package-level style imports for component libraries.
161
162
```typescript { .api }
163
/**
164
* Options for package style generation
165
*/
166
interface StyleGenOptions {
167
/** Output path for generated style file */
168
outputPath?: string;
169
/** Custom path resolver function */
170
pathResolver?: (path: string) => string;
171
}
172
173
/**
174
* Generates package-level style imports file
175
* Creates index file that imports all component styles
176
* @param options - Generation options
177
* @returns Generated style content or void if written to file
178
*/
179
function genPackageStyle(options?: StyleGenOptions): void | string;
180
```
181
182
**Usage:**
183
```typescript
184
import { genPackageStyle } from "@vant/cli";
185
186
// Generate package styles with default settings
187
genPackageStyle();
188
189
// Custom output path
190
genPackageStyle({
191
outputPath: './lib/style.css',
192
pathResolver: (path) => path.replace(/\.less$/, '.css')
193
});
194
```
195
196
### Dependency Analysis
197
198
Analysis and management of import dependencies in the build process.
199
200
```typescript { .api }
201
/**
202
* File path resolution result
203
*/
204
interface FilePathResult {
205
/** Resolved file path with extension */
206
path: string;
207
/** Whether the path points to an index file */
208
isIndex: boolean;
209
}
210
211
/**
212
* Resolves file path with appropriate extension
213
* @param filePath - Input file path (may be missing extension)
214
* @returns Resolved path information
215
*/
216
function fillExt(filePath: string): FilePathResult;
217
218
/**
219
* Clears internal dependency cache
220
* Used to reset dependency tracking between builds
221
*/
222
function clearDepsCache(): void;
223
224
/**
225
* Gets all file dependencies for a given file
226
* @param filePath - Path to analyze for dependencies
227
* @returns Array of dependency file paths
228
*/
229
function getDeps(filePath: string): string[];
230
231
/**
232
* Replaces import extensions in script code
233
* @param code - Source code containing import statements
234
* @param filePath - Current file path for context
235
* @param ext - Target extension to use
236
* @returns Code with updated import extensions
237
*/
238
function replaceScriptImportExt(code: string, filePath: string, ext: string): string;
239
```
240
241
**Usage:**
242
```typescript
243
import { getDeps, fillExt, replaceScriptImportExt } from "@vant/cli";
244
245
// Analyze file dependencies
246
const deps = getDeps('./src/button/index.ts');
247
console.log('Dependencies:', deps);
248
249
// Resolve file extension
250
const resolved = fillExt('./src/button/index');
251
console.log(resolved); // { path: './src/button/index.ts', isIndex: true }
252
253
// Update import extensions
254
const code = `import Button from './button';`;
255
const updatedCode = replaceScriptImportExt(code, './src/index.ts', '.js');
256
console.log(updatedCode); // import Button from './button.js';
257
```
258
259
### WebStorm Type Definitions
260
261
Generation of IDE type definitions for better development experience.
262
263
```typescript { .api }
264
/**
265
* Vue component slot definition
266
*/
267
interface VueSlot {
268
name: string;
269
description: string;
270
}
271
272
/**
273
* Vue component event argument
274
*/
275
interface VueEventArgument {
276
name: string;
277
type: string;
278
}
279
280
/**
281
* Vue component event definition
282
*/
283
interface VueEvent {
284
name: string;
285
description?: string;
286
arguments?: VueEventArgument[];
287
}
288
289
/**
290
* Vue component attribute definition
291
*/
292
interface VueAttribute {
293
name: string;
294
default: string;
295
description: string;
296
value: {
297
kind: 'expression';
298
type: string;
299
};
300
}
301
302
/**
303
* Vue component tag definition for IDE
304
*/
305
interface VueTag {
306
name: string;
307
slots?: VueSlot[];
308
events?: VueEvent[];
309
attributes?: VueAttribute[];
310
description?: string;
311
}
312
313
/**
314
* Web types generation options
315
*/
316
interface WebTypesOptions {
317
name: string;
318
path: PathLike;
319
test: RegExp;
320
version: string;
321
outputDir?: string;
322
tagPrefix?: string;
323
}
324
325
/**
326
* Parses markdown documentation and generates web-types
327
* @param options - Generation options
328
* @returns Promise that resolves when generation is complete
329
*/
330
function parseAndWrite(options: WebTypesOptions): Promise<void>;
331
332
/**
333
* Generates WebStorm type definitions for Vue components
334
* @param tagPrefix - Optional prefix for component tags
335
*/
336
function genWebStormTypes(tagPrefix?: string): void;
337
```
338
339
**Usage:**
340
```typescript
341
import { genWebStormTypes, parseAndWrite } from "@vant/cli";
342
343
// Generate WebStorm types
344
genWebStormTypes('van');
345
346
// Parse markdown and generate types
347
await parseAndWrite({
348
name: 'MyLibrary',
349
path: './docs',
350
test: /\.md$/,
351
version: '1.0.0',
352
tagPrefix: 'my'
353
});
354
```
355
356
## Build Pipeline Integration
357
358
The build system integrates all compilation steps into a cohesive pipeline:
359
360
```typescript
361
// Example build pipeline usage
362
import {
363
clean,
364
compileSfc,
365
compileStyle,
366
compileBundles,
367
genPackageStyle,
368
genWebStormTypes
369
} from "@vant/cli";
370
371
async function buildLibrary() {
372
// 1. Clean previous builds
373
await clean();
374
375
// 2. Compile Vue components
376
const components = await getComponents();
377
for (const component of components) {
378
await compileSfc(`./src/${component}/index.vue`);
379
await compileStyle(`./src/${component}/index.less`);
380
}
381
382
// 3. Generate package styles
383
genPackageStyle();
384
385
// 4. Generate bundles
386
await compileBundles();
387
388
// 5. Generate IDE support
389
genWebStormTypes();
390
}
391
```
392
393
## Output Structure
394
395
The build system generates the following output structure:
396
397
```
398
lib/ # CommonJS modules
399
├── button/
400
│ ├── index.js # Compiled component
401
│ ├── index.css # Component styles
402
│ └── index.d.ts # TypeScript declarations
403
└── index.js # Main entry point
404
405
es/ # ES modules
406
├── button/
407
│ ├── index.js # Compiled component (ESM)
408
│ ├── index.css # Component styles
409
│ └── index.d.ts # TypeScript declarations
410
└── index.js # Main entry point (ESM)
411
412
dist/ # Bundled outputs
413
├── index.js # UMD bundle
414
├── index.min.js # Minified UMD bundle
415
└── index.css # Combined styles
416
417
site-dist/ # Documentation site
418
└── [static files]
419
```
420
421
## Configuration Integration
422
423
The build system respects configuration from `vant.config.mjs`:
424
425
```typescript
426
// Build-related configuration options
427
interface BuildConfig {
428
/** Source directory (default: 'src') */
429
srcDir?: string;
430
/** Component tag prefix */
431
tagPrefix?: string;
432
/** Enable named exports */
433
namedExport?: boolean;
434
/** CSS preprocessor configuration */
435
css?: {
436
preprocessor?: 'css' | 'less' | 'sass';
437
base?: string;
438
removeSourceFile?: boolean;
439
};
440
/** Bundle configurations */
441
bundleOptions?: BundleOption[];
442
/** Custom Vite configuration */
443
configureVite?: (config: InlineConfig) => InlineConfig | void;
444
}
445
```