This repository was archived by the owner on May 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 309
/
Copy pathwebpack.ts
257 lines (216 loc) · 9.08 KB
/
webpack.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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
import { EventEmitter } from 'events';
import { dirname, join } from 'path';
import * as webpackApi from 'webpack';
import { Logger } from './logger/logger';
import { fillConfigDefaults, getUserConfigFile, replacePathVars } from './util/config';
import * as Constants from './util/constants';
import { BuildError, IgnorableError } from './util/errors';
import { emit, EventType } from './util/events';
import { getBooleanPropertyValue, printDependencyMap, webpackStatsToDependencyMap, writeFileAsync } from './util/helpers';
import { BuildContext, BuildState, ChangedFile, TaskInfo } from './util/interfaces';
const eventEmitter = new EventEmitter();
const INCREMENTAL_BUILD_FAILED = 'incremental_build_failed';
const INCREMENTAL_BUILD_SUCCESS = 'incremental_build_success';
/*
* Due to how webpack watch works, sometimes we start an update event
* but it doesn't affect the bundle at all, for example adding a new typescript file
* not imported anywhere or adding an html file not used anywhere.
* In this case, we'll be left hanging and have screwed up logging when the bundle is modified
* because multiple promises will resolve at the same time (we queue up promises waiting for an event to occur)
* To mitigate this, store pending "webpack watch"/bundle update promises in this array and only resolve the
* the most recent one. reject all others at that time with an IgnorableError.
*/
let pendingPromises: Promise<any>[] = [];
export function webpack(context: BuildContext, configFile: string) {
configFile = getUserConfigFile(context, taskInfo, configFile);
const logger = new Logger('webpack');
return webpackWorker(context, configFile)
.then(() => {
context.bundleState = BuildState.SuccessfulBuild;
logger.finish();
})
.catch(err => {
context.bundleState = BuildState.RequiresBuild;
throw logger.fail(err);
});
}
export function webpackUpdate(changedFiles: ChangedFile[], context: BuildContext, configFile?: string) {
const logger = new Logger('webpack update');
const webpackConfig = getWebpackConfig(context, configFile);
Logger.debug('webpackUpdate: Starting Incremental Build');
const promisetoReturn = runWebpackIncrementalBuild(false, context, webpackConfig);
emit(EventType.WebpackFilesChanged, null);
return promisetoReturn.then((stats: any) => {
// the webpack incremental build finished, so reset the list of pending promises
pendingPromises = [];
Logger.debug('webpackUpdate: Incremental Build Done, processing Data');
return webpackBuildComplete(stats, context, webpackConfig);
}).then(() => {
context.bundleState = BuildState.SuccessfulBuild;
return logger.finish();
}).catch(err => {
context.bundleState = BuildState.RequiresBuild;
if (err instanceof IgnorableError) {
throw err;
}
throw logger.fail(err);
});
}
export function webpackWorker(context: BuildContext, configFile: string): Promise<any> {
const webpackConfig = getWebpackConfig(context, configFile);
let promise: Promise<any> = null;
if (context.isWatch) {
promise = runWebpackIncrementalBuild(!context.webpackWatch, context, webpackConfig);
} else {
promise = runWebpackFullBuild(webpackConfig);
}
return promise
.then((stats: any) => {
return webpackBuildComplete(stats, context, webpackConfig);
});
}
function webpackBuildComplete(stats: any, context: BuildContext, webpackConfig: WebpackConfig) {
if (getBooleanPropertyValue(Constants.ENV_PRINT_WEBPACK_DEPENDENCY_TREE)) {
Logger.debug('Webpack Dependency Map Start');
const dependencyMap = webpackStatsToDependencyMap(context, stats);
printDependencyMap(dependencyMap);
Logger.debug('Webpack Dependency Map End');
}
// set the module files used in this bundle
// this reference can be used elsewhere in the build (sass)
const files: string[] = [];
stats.compilation.modules.forEach((webpackModule: any) => {
if (webpackModule.resource) {
files.push(webpackModule.resource);
} else if (webpackModule.context) {
files.push(webpackModule.context);
} else if (webpackModule.fileDependencies) {
webpackModule.fileDependencies.forEach((filePath: string) => {
files.push(filePath);
});
}
});
const trimmedFiles = files.filter(file => file && file.length > 0);
context.moduleFiles = trimmedFiles;
return setBundledFiles(context);
}
export function setBundledFiles(context: BuildContext) {
const bundledFilesToWrite = context.fileCache.getAll().filter(file => {
return dirname(file.path).indexOf(context.buildDir) >= 0 && (file.path.endsWith('.js') || file.path.endsWith('.js.map'));
});
context.bundledFilePaths = bundledFilesToWrite.map(bundledFile => bundledFile.path);
}
export function runWebpackFullBuild(config: WebpackConfig) {
return new Promise((resolve, reject) => {
const callback = (err: Error, stats: any) => {
if (err) {
reject(new BuildError(err));
} else {
const info = stats.toJson();
if (stats.hasErrors()) {
reject(new BuildError(info.errors));
} else if (stats.hasWarnings()) {
Logger.debug(info.warnings);
resolve(stats);
} else {
resolve(stats);
}
}
};
const compiler = webpackApi(config as any);
compiler.run(callback);
});
}
function runWebpackIncrementalBuild(initializeWatch: boolean, context: BuildContext, config: WebpackConfig) {
const promise = new Promise((resolve, reject) => {
// start listening for events, remove listeners once an event is received
eventEmitter.on(INCREMENTAL_BUILD_FAILED, (err: Error) => {
Logger.debug('Webpack Bundle Update Failed');
eventEmitter.removeAllListeners();
handleWebpackBuildFailure(resolve, reject, err, promise, pendingPromises);
});
eventEmitter.on(INCREMENTAL_BUILD_SUCCESS, (stats: any) => {
Logger.debug('Webpack Bundle Updated');
eventEmitter.removeAllListeners();
handleWebpackBuildSuccess(resolve, reject, stats, promise, pendingPromises);
});
if (initializeWatch) {
startWebpackWatch(context, config);
}
});
pendingPromises.push(promise);
return promise;
}
function handleWebpackBuildFailure(resolve: Function, reject: Function, error: Error, promise: Promise<any>, pendingPromises: Promise<void>[]) {
// check if the promise if the last promise in the list of pending promises
if (pendingPromises.length > 0 && pendingPromises[pendingPromises.length - 1] === promise) {
// reject this one with a build error
reject(new BuildError(error));
return;
}
// for all others, reject with an ignorable error
reject(new IgnorableError());
}
function handleWebpackBuildSuccess(resolve: Function, reject: Function, stats: any, promise: Promise<any>, pendingPromises: Promise<void>[]) {
// check if the promise if the last promise in the list of pending promises
if (pendingPromises.length > 0 && pendingPromises[pendingPromises.length - 1] === promise) {
Logger.debug('handleWebpackBuildSuccess: Resolving with Webpack data');
resolve(stats);
return;
}
// for all others, reject with an ignorable error
Logger.debug('handleWebpackBuildSuccess: Rejecting with ignorable error');
reject(new IgnorableError());
}
function startWebpackWatch(context: BuildContext, config: WebpackConfig) {
Logger.debug('Starting Webpack watch');
const compiler = webpackApi(config as any);
context.webpackWatch = compiler.watch({}, (err: Error, stats: any) => {
if (err) {
eventEmitter.emit(INCREMENTAL_BUILD_FAILED, err);
} else {
eventEmitter.emit(INCREMENTAL_BUILD_SUCCESS, stats);
}
});
}
export function getWebpackConfig(context: BuildContext, configFile: string): WebpackConfig {
configFile = getUserConfigFile(context, taskInfo, configFile);
const webpackConfigDictionary = fillConfigDefaults(configFile, taskInfo.defaultConfigFile);
const webpackConfig: WebpackConfig = getWebpackConfigFromDictionary(context, webpackConfigDictionary);
webpackConfig.entry = replacePathVars(context, webpackConfig.entry);
webpackConfig.output.path = replacePathVars(context, webpackConfig.output.path);
return webpackConfig;
}
export function getWebpackConfigFromDictionary(context: BuildContext, webpackConfigDictionary: any): WebpackConfig {
// todo, support more ENV here
if (context.runAot) {
return webpackConfigDictionary['prod'];
}
return webpackConfigDictionary['dev'];
}
export function getOutputDest(context: BuildContext) {
const webpackConfig = getWebpackConfig(context, null);
return join(webpackConfig.output.path, webpackConfig.output.filename);
}
const taskInfo: TaskInfo = {
fullArg: '--webpack',
shortArg: '-w',
envVar: 'IONIC_WEBPACK',
packageConfig: 'ionic_webpack',
defaultConfigFile: 'webpack.config'
};
export interface WebpackConfig {
// https://www.npmjs.com/package/webpack
devtool: string;
entry: string | { [key: string]: any };
output: WebpackOutputObject;
resolve: WebpackResolveObject;
}
export interface WebpackOutputObject {
path: string;
filename: string;
}
export interface WebpackResolveObject {
extensions: string[];
modules: string[];
}