0
# Programmatic API
1
2
Core Node.js API for building and serving styleguides programmatically. This API enables integration with custom build systems, CI/CD pipelines, and automated workflows.
3
4
## Capabilities
5
6
### Main API Function
7
8
Initialize the Styleguidist API with configuration options.
9
10
```typescript { .api }
11
/**
12
* Initialize Styleguidist API
13
* @param config - Configuration object or path to config file (optional)
14
* @returns API object with build, server, and makeWebpackConfig methods
15
*/
16
function styleguidist(config?: StyleguidistConfig | string): StyleguidistAPI;
17
18
interface StyleguidistAPI {
19
build(callback: BuildCallback): webpack.Compiler;
20
server(callback: ServerCallback): ServerInfo;
21
makeWebpackConfig(env?: WebpackEnv): webpack.Configuration;
22
}
23
```
24
25
**Usage Examples:**
26
27
```javascript
28
const styleguidist = require('react-styleguidist');
29
30
// Initialize with inline configuration
31
const api = styleguidist({
32
components: 'src/components/**/*.{js,jsx}',
33
styleguideDir: 'dist/styleguide'
34
});
35
36
// Initialize with config file path
37
const api = styleguidist('./styleguide.config.js');
38
39
// Initialize with default config (looks for styleguide.config.js)
40
const api = styleguidist();
41
```
42
43
### Build Method
44
45
Build a static styleguide for production deployment.
46
47
```typescript { .api }
48
/**
49
* Build static styleguide
50
* @param callback - Function called when build completes or fails
51
* @returns Webpack compiler instance for advanced usage
52
*/
53
build(callback: BuildCallback): webpack.Compiler;
54
55
type BuildCallback = (
56
err: Error | null,
57
config: SanitizedStyleguidistConfig,
58
stats: webpack.Stats
59
) => void;
60
```
61
62
**Usage Examples:**
63
64
```javascript
65
const styleguidist = require('react-styleguidist');
66
67
const api = styleguidist({
68
components: 'src/components/**/*.jsx',
69
styleguideDir: 'build/styleguide'
70
});
71
72
// Basic build
73
api.build((err, config, stats) => {
74
if (err) {
75
console.error('Build failed:', err.message);
76
process.exit(1);
77
}
78
79
console.log('Styleguide built successfully!');
80
console.log('Output directory:', config.styleguideDir);
81
console.log('Build time:', stats.endTime - stats.startTime, 'ms');
82
});
83
84
// Advanced usage with compiler access
85
const compiler = api.build((err, config, stats) => {
86
// Handle build completion
87
});
88
89
// Access webpack hooks for advanced customization
90
compiler.hooks.done.tap('CustomPlugin', (stats) => {
91
console.log('Custom build processing...');
92
});
93
```
94
95
### Server Method
96
97
Start a development server with hot reloading for component development.
98
99
```typescript { .api }
100
/**
101
* Start development server
102
* @param callback - Function called when server starts or fails
103
* @returns Object containing WebpackDevServer app and webpack compiler
104
*/
105
server(callback: ServerCallback): ServerInfo;
106
107
type ServerCallback = (
108
err: Error | undefined,
109
config: SanitizedStyleguidistConfig
110
) => void;
111
112
interface ServerInfo {
113
app: WebpackDevServer;
114
compiler: webpack.Compiler;
115
}
116
```
117
118
**Usage Examples:**
119
120
```javascript
121
const styleguidist = require('react-styleguidist');
122
123
const api = styleguidist({
124
components: 'src/components/**/*.jsx',
125
serverPort: 8080,
126
serverHost: 'localhost'
127
});
128
129
// Start development server
130
const serverInfo = api.server((err, config) => {
131
if (err) {
132
console.error('Server failed to start:', err.message);
133
return;
134
}
135
136
console.log(`Server running at http://${config.serverHost}:${config.serverPort}`);
137
});
138
139
// Access server and compiler for advanced usage
140
const { app, compiler } = serverInfo;
141
142
// Add custom middleware
143
app.app.use('/custom', (req, res) => {
144
res.json({ message: 'Custom endpoint' });
145
});
146
147
// Hook into webpack compilation
148
compiler.hooks.done.tap('DevServerPlugin', (stats) => {
149
if (stats.hasErrors()) {
150
console.log('Compilation errors detected');
151
}
152
});
153
```
154
155
### Make Webpack Config Method
156
157
Generate the webpack configuration used by Styleguidist without running build or server.
158
159
```typescript { .api }
160
/**
161
* Generate webpack configuration
162
* @param env - Target environment (defaults to 'production')
163
* @returns Complete webpack configuration object
164
*/
165
makeWebpackConfig(env?: WebpackEnv): webpack.Configuration;
166
167
type WebpackEnv = 'development' | 'production' | 'none';
168
```
169
170
**Usage Examples:**
171
172
```javascript
173
const styleguidist = require('react-styleguidist');
174
175
const api = styleguidist({
176
components: 'src/components/**/*.jsx'
177
});
178
179
// Get production webpack config
180
const prodConfig = api.makeWebpackConfig('production');
181
console.log('Entry points:', prodConfig.entry);
182
console.log('Output path:', prodConfig.output.path);
183
184
// Get development webpack config
185
const devConfig = api.makeWebpackConfig('development');
186
console.log('Dev server config:', devConfig.devServer);
187
188
// Use config with custom webpack setup
189
const webpack = require('webpack');
190
const compiler = webpack(prodConfig);
191
192
compiler.run((err, stats) => {
193
if (err || stats.hasErrors()) {
194
console.error('Custom build failed');
195
} else {
196
console.log('Custom build completed');
197
}
198
});
199
```
200
201
### Advanced Integration Patterns
202
203
**Custom Build Pipeline:**
204
205
```javascript
206
const styleguidist = require('react-styleguidist');
207
const fs = require('fs');
208
const path = require('path');
209
210
async function buildStyleguideWithAssets() {
211
const api = styleguidist('./styleguide.config.js');
212
213
return new Promise((resolve, reject) => {
214
api.build((err, config, stats) => {
215
if (err) return reject(err);
216
217
// Copy additional assets
218
const assetsDir = path.join(config.styleguideDir, 'assets');
219
fs.mkdirSync(assetsDir, { recursive: true });
220
fs.copyFileSync('logo.png', path.join(assetsDir, 'logo.png'));
221
222
// Generate build manifest
223
const manifest = {
224
buildTime: new Date().toISOString(),
225
outputPath: config.styleguideDir,
226
assets: stats.toJson().assets.map(asset => asset.name)
227
};
228
229
fs.writeFileSync(
230
path.join(config.styleguideDir, 'build-manifest.json'),
231
JSON.stringify(manifest, null, 2)
232
);
233
234
resolve(config);
235
});
236
});
237
}
238
```
239
240
**Development Server with Custom Setup:**
241
242
```javascript
243
const styleguidist = require('react-styleguidist');
244
const express = require('express');
245
246
function startDevEnvironment() {
247
const api = styleguidist({
248
components: 'src/components/**/*.jsx',
249
serverPort: 3001
250
});
251
252
const { app, compiler } = api.server((err, config) => {
253
if (err) {
254
console.error('Dev server error:', err);
255
return;
256
}
257
console.log('Styleguidist server ready');
258
});
259
260
// Add API endpoints to the dev server
261
app.app.use('/api', express.json());
262
app.app.post('/api/feedback', (req, res) => {
263
console.log('Component feedback:', req.body);
264
res.json({ status: 'received' });
265
});
266
267
// Monitor compilation for notifications
268
compiler.hooks.done.tap('NotificationPlugin', (stats) => {
269
if (!stats.hasErrors()) {
270
console.log('✓ Components updated successfully');
271
}
272
});
273
}
274
```
275
276
## Type Definitions
277
278
```typescript { .api }
279
interface SanitizedStyleguidistConfig {
280
components: string | string[] | (() => string[]);
281
sections: ConfigSection[];
282
styleguideDir: string;
283
serverHost: string;
284
serverPort: number;
285
webpackConfig: webpack.Configuration | ((env?: string) => webpack.Configuration);
286
dangerouslyUpdateWebpackConfig: (config: webpack.Configuration, env: string) => webpack.Configuration;
287
updateWebpackConfig: (config: webpack.Configuration) => webpack.Configuration;
288
theme: RecursivePartial<Theme>;
289
styles: ((theme: Theme) => Styles) | Styles;
290
template: any;
291
title: string;
292
verbose: boolean;
293
// ... many additional configuration properties
294
}
295
296
interface ConfigSection {
297
name?: string;
298
content?: string;
299
components?: string | string[] | (() => string[]);
300
sections?: ConfigSection[];
301
description?: string;
302
exampleMode?: ExpandMode;
303
usageMode?: ExpandMode;
304
}
305
```