-
-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
index.ts
166 lines (135 loc) · 4.82 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import webpack, { Stats, Configuration, ProgressPlugin } from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import { logger } from '@storybook/node-logger';
import { useProgressReporting, checkWebpackVersion } from '@storybook/core-common';
import type { Builder, Options } from '@storybook/core-common';
let compilation: ReturnType<typeof webpackDevMiddleware>;
let reject: (reason?: any) => void;
type WebpackBuilder = Builder<Configuration, Stats>;
export const getConfig: WebpackBuilder['getConfig'] = async (options) => {
const { presets } = options;
const typescriptOptions = await presets.apply('typescript', {}, options);
const babelOptions = await presets.apply('babel', {}, { ...options, typescriptOptions });
const frameworkOptions = await presets.apply(`${options.framework}Options`, {}, options);
return presets.apply(
'webpack',
{},
{
...options,
babelOptions,
typescriptOptions,
[`${options.framework}Options`]: frameworkOptions,
}
) as any;
};
export const executor = {
get: async (options: Options) => {
const version = ((await options.presets.apply('webpackVersion')) || '5') as string;
const webpackInstance =
(await options.presets.apply<{ default: typeof webpack }>('webpackInstance'))?.default ||
webpack;
checkWebpackVersion({ version }, '5', 'builder-webpack5');
return webpackInstance;
},
};
export const start: WebpackBuilder['start'] = async ({ startTime, options, router }) => {
const webpackInstance = await executor.get(options);
const config = await getConfig(options);
const compiler = webpackInstance(config);
if (!compiler) {
const err = `${config.name}: missing webpack compiler at runtime!`;
logger.error(err);
return {
bail,
totalTime: process.hrtime(startTime),
stats: {
hasErrors: () => true,
hasWarnings: () => false,
toJson: () => ({ warnings: [] as any[], errors: [err] }),
} as any as Stats,
};
}
const { handler, modulesCount } = await useProgressReporting(router, startTime, options);
new ProgressPlugin({ handler, modulesCount }).apply(compiler);
const middlewareOptions: Parameters<typeof webpackDevMiddleware>[1] = {
publicPath: config.output?.publicPath as string,
writeToDisk: true,
};
compilation = webpackDevMiddleware(compiler, middlewareOptions);
router.use(compilation);
router.use(webpackHotMiddleware(compiler as any));
const stats = await new Promise<Stats>((ready, stop) => {
compilation.waitUntilValid(ready);
reject = stop;
});
if (!stats) {
throw new Error('no stats after building preview');
}
if (stats.hasErrors()) {
throw stats;
}
return {
bail,
stats,
totalTime: process.hrtime(startTime),
};
};
export const bail: WebpackBuilder['bail'] = (e: Error) => {
if (reject) {
reject();
}
if (process) {
try {
compilation.close();
logger.warn('Force closed preview build');
} catch (err) {
logger.warn('Unable to close preview build!');
}
}
throw e;
};
export const build: WebpackBuilder['build'] = async ({ options, startTime }) => {
const webpackInstance = await executor.get(options);
logger.info('=> Compiling preview..');
const config = await getConfig(options);
return new Promise((succeed, fail) => {
const compiler = webpackInstance(config);
compiler.run((error, stats) => {
if (error || !stats || stats.hasErrors()) {
logger.error('=> Failed to build the preview');
process.exitCode = 1;
if (error) {
logger.error(error.message);
compiler.close(() => fail(error));
return;
}
if (stats && (stats.hasErrors() || stats.hasWarnings())) {
const { warnings = [], errors = [] } = stats.toJson({ warnings: true, errors: true });
errors.forEach((e) => logger.error(e.message));
warnings.forEach((e) => logger.error(e.message));
compiler.close(() =>
options.debugWebpack
? fail(stats)
: fail(new Error('=> Webpack failed, learn more with --debug-webpack'))
);
return;
}
}
logger.trace({ message: '=> Preview built', time: process.hrtime(startTime) });
if (stats && stats.hasWarnings()) {
stats.toJson({ warnings: true }).warnings.forEach((e) => logger.warn(e.message));
}
// https://webpack.js.org/api/node/#run
// #15227
compiler.close((closeErr) => {
if (closeErr) {
return fail(closeErr);
}
return succeed(stats);
});
});
});
};
export const corePresets = [require.resolve('./presets/preview-preset.js')];
export const overridePresets = [require.resolve('./presets/custom-webpack-preset.js')];