-
Notifications
You must be signed in to change notification settings - Fork 12k
/
Copy pathindex.ts
292 lines (266 loc) · 9.58 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
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {
BuilderContext,
BuilderOutput,
createBuilder,
} from '@angular-devkit/architect';
import {
BuildResult,
EmittedFiles,
WebpackLoggingCallback,
runWebpack,
} from '@angular-devkit/build-webpack';
import {
experimental,
getSystemPath,
join,
json,
logging,
normalize,
resolve,
tags,
virtualFs,
} from '@angular-devkit/core';
import { NodeJsSyncHost } from '@angular-devkit/core/node';
import * as fs from 'fs';
import * as path from 'path';
import { from, of } from 'rxjs';
import { bufferCount, catchError, concatMap, map, mergeScan, switchMap } from 'rxjs/operators';
import { ScriptTarget } from 'typescript';
import * as webpack from 'webpack';
import { NgBuildAnalyticsPlugin } from '../../plugins/webpack/analytics';
import { WebpackConfigOptions } from '../angular-cli-files/models/build-options';
import {
getAotConfig,
getBrowserConfig,
getCommonConfig,
getNonAotConfig,
getStatsConfig,
getStylesConfig,
getWorkerConfig,
} from '../angular-cli-files/models/webpack-configs';
import {
IndexHtmlTransform,
writeIndexHtml,
} from '../angular-cli-files/utilities/index-file/write-index-html';
import { readTsconfig } from '../angular-cli-files/utilities/read-tsconfig';
import { augmentAppWithServiceWorker } from '../angular-cli-files/utilities/service-worker';
import {
statsErrorsToString,
statsToString,
statsWarningsToString,
} from '../angular-cli-files/utilities/stats';
import { ExecutionTransformer } from '../transforms';
import { deleteOutputDir, isEs5SupportNeeded } from '../utils';
import { Version } from '../utils/version';
import { generateBrowserWebpackConfigFromContext } from '../utils/webpack-browser-config';
import { Schema as BrowserBuilderSchema } from './schema';
export type BrowserBuilderOutput = json.JsonObject & BuilderOutput & {
outputPath: string;
};
export function createBrowserLoggingCallback(
verbose: boolean,
logger: logging.LoggerApi,
): WebpackLoggingCallback {
return (stats, config) => {
// config.stats contains our own stats settings, added during buildWebpackConfig().
const json = stats.toJson(config.stats);
if (verbose) {
logger.info(stats.toString(config.stats));
} else {
logger.info(statsToString(json, config.stats));
}
if (stats.hasWarnings()) {
logger.warn(statsWarningsToString(json, config.stats));
}
if (stats.hasErrors()) {
logger.error(statsErrorsToString(json, config.stats));
}
};
}
export async function buildBrowserWebpackConfigFromContext(
options: BrowserBuilderSchema,
context: BuilderContext,
host: virtualFs.Host<fs.Stats> = new NodeJsSyncHost(),
): Promise<{ workspace: experimental.workspace.Workspace, config: webpack.Configuration[] }> {
return generateBrowserWebpackConfigFromContext(
options,
context,
wco => [
getCommonConfig(wco),
getBrowserConfig(wco),
getStylesConfig(wco),
getStatsConfig(wco),
getAnalyticsConfig(wco, context),
getCompilerConfig(wco),
wco.buildOptions.webWorkerTsConfig ? getWorkerConfig(wco) : {},
],
host,
);
}
function getAnalyticsConfig(
wco: WebpackConfigOptions,
context: BuilderContext,
): webpack.Configuration {
if (context.analytics) {
// If there's analytics, add our plugin. Otherwise no need to slow down the build.
let category = 'build';
if (context.builder) {
// We already vetted that this is a "safe" package, otherwise the analytics would be noop.
category = context.builder.builderName.split(':')[1];
}
// The category is the builder name if it's an angular builder.
return {
plugins: [
new NgBuildAnalyticsPlugin(wco.projectRoot, context.analytics, category),
],
};
}
return {};
}
function getCompilerConfig(wco: WebpackConfigOptions): webpack.Configuration {
if (wco.buildOptions.main || wco.buildOptions.polyfills) {
return wco.buildOptions.aot ? getAotConfig(wco) : getNonAotConfig(wco);
}
return {};
}
async function initialize(
options: BrowserBuilderSchema,
context: BuilderContext,
host: virtualFs.Host<fs.Stats>,
webpackConfigurationTransform?: ExecutionTransformer<webpack.Configuration>,
): Promise<{ workspace: experimental.workspace.Workspace, config: webpack.Configuration[] }> {
const { config, workspace } = await buildBrowserWebpackConfigFromContext(options, context, host);
let transformedConfig;
if (webpackConfigurationTransform) {
transformedConfig = [];
for (const c of config) {
transformedConfig.push(await webpackConfigurationTransform(c));
}
}
if (options.deleteOutputPath) {
await deleteOutputDir(
normalize(context.workspaceRoot),
normalize(options.outputPath),
host,
).toPromise();
}
return { config: transformedConfig || config, workspace };
}
export function buildWebpackBrowser(
options: BrowserBuilderSchema,
context: BuilderContext,
transforms: {
webpackConfiguration?: ExecutionTransformer<webpack.Configuration>,
logging?: WebpackLoggingCallback,
indexHtml?: IndexHtmlTransform,
} = {},
) {
const host = new NodeJsSyncHost();
const root = normalize(context.workspaceRoot);
// Check Angular version.
Version.assertCompatibleAngularVersion(context.workspaceRoot);
const loggingFn = transforms.logging
|| createBrowserLoggingCallback(!!options.verbose, context.logger);
return from(initialize(options, context, host, transforms.webpackConfiguration)).pipe(
switchMap(({ workspace, config: configs }) => {
const projectName = context.target
? context.target.project : workspace.getDefaultProjectName();
if (!projectName) {
throw new Error('Must either have a target from the context or a default project.');
}
const projectRoot = resolve(
workspace.root,
normalize(workspace.getProject(projectName).root),
);
const tsConfigPath = path.resolve(getSystemPath(workspace.root), options.tsConfig);
const tsConfig = readTsconfig(tsConfigPath);
if (isEs5SupportNeeded(projectRoot) &&
tsConfig.options.target !== ScriptTarget.ES5 &&
tsConfig.options.target !== ScriptTarget.ES2015) {
context.logger.warn(tags.stripIndent`
WARNING: Using differential loading with targets ES5 and ES2016 or higher may
cause problems. Browsers with support for ES2015 will load the ES2016+ scripts
referenced with script[type="module"] but they may not support ES2016+ syntax.
`);
}
return from(configs).pipe(
// the concurrency parameter (3rd parameter of mergeScan) is deliberately
// set to 1 to make sure the build steps are executed in sequence.
mergeScan((lastResult, config) => {
// Make sure to only run the 2nd build step, if 1st one succeeded
if (lastResult.success) {
return runWebpack(config, context, { logging: loggingFn });
} else {
return of();
}
}, { success: true } as BuildResult, 1),
bufferCount(configs.length),
switchMap(buildEvents => {
const success = buildEvents.every(r => r.success);
if (success && options.index) {
let noModuleFiles: EmittedFiles[] | undefined;
let moduleFiles: EmittedFiles[] | undefined;
let files: EmittedFiles[] | undefined;
const [ES5Result, ES2015Result] = buildEvents;
if (buildEvents.length === 2) {
noModuleFiles = ES5Result.emittedFiles;
moduleFiles = ES2015Result.emittedFiles || [];
files = moduleFiles.filter(x => x.extension === '.css');
} else {
const { emittedFiles = [] } = ES5Result;
files = emittedFiles.filter(x => x.name !== 'polyfills-es5');
noModuleFiles = emittedFiles.filter(x => x.name === 'polyfills-es5');
}
return writeIndexHtml({
host,
outputPath: resolve(root, normalize(options.outputPath)),
indexPath: join(root, options.index),
files,
noModuleFiles,
moduleFiles,
baseHref: options.baseHref,
deployUrl: options.deployUrl,
sri: options.subresourceIntegrity,
scripts: options.scripts,
styles: options.styles,
postTransform: transforms.indexHtml,
})
.pipe(
map(() => ({ success: true })),
catchError(() => of({ success: false })),
);
} else {
return of({ success });
}
}),
concatMap(buildEvent => {
if (buildEvent.success && !options.watch && options.serviceWorker) {
return from(augmentAppWithServiceWorker(
host,
root,
projectRoot,
resolve(root, normalize(options.outputPath)),
options.baseHref || '/',
options.ngswConfigPath,
).then(() => ({ success: true }), () => ({ success: false })));
} else {
return of(buildEvent);
}
}),
map(event => ({
...event,
// If we use differential loading, both configs have the same outputs
outputPath: path.resolve(context.workspaceRoot, options.outputPath),
} as BrowserBuilderOutput)),
);
}),
);
}
export default createBuilder<json.JsonObject & BrowserBuilderSchema>(buildWebpackBrowser);