-
Notifications
You must be signed in to change notification settings - Fork 12k
/
Copy pathindex.ts
449 lines (401 loc) · 15.3 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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
/**
* @license
* Copyright Google LLC 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, createBuilder, targetFromTargetString } from '@angular-devkit/architect';
import {
DevServerBuildOutput,
WebpackLoggingCallback,
runWebpackDevServer,
} from '@angular-devkit/build-webpack';
import { json, tags } from '@angular-devkit/core';
import * as path from 'path';
import { Observable, from } from 'rxjs';
import { concatMap, switchMap } from 'rxjs/operators';
import * as ts from 'typescript';
import * as url from 'url';
import webpack from 'webpack';
import webpackDevServer from 'webpack-dev-server';
import { Schema as BrowserBuilderSchema, OutputHashing } from '../browser/schema';
import { ExecutionTransformer } from '../transforms';
import { BuildBrowserFeatures, normalizeOptimization } from '../utils';
import { findCachePath } from '../utils/cache-path';
import { checkPort } from '../utils/check-port';
import { colors } from '../utils/color';
import { I18nOptions } from '../utils/i18n-options';
import { IndexHtmlTransform } from '../utils/index-file/index-html-generator';
import { generateEntryPoints } from '../utils/package-chunk-sort';
import { readTsconfig } from '../utils/read-tsconfig';
import { assertCompatibleAngularVersion } from '../utils/version';
import {
generateI18nBrowserWebpackConfigFromContext,
getIndexInputFile,
getIndexOutputFile,
} from '../utils/webpack-browser-config';
import {
getAnalyticsConfig,
getBrowserConfig,
getCommonConfig,
getDevServerConfig,
getStatsConfig,
getStylesConfig,
getTypeScriptConfig,
getWorkerConfig,
} from '../webpack/configs';
import { IndexHtmlWebpackPlugin } from '../webpack/plugins/index-html-webpack-plugin';
import { createWebpackLoggingCallback } from '../webpack/utils/stats';
import { Schema } from './schema';
export type DevServerBuilderOptions = Schema & json.JsonObject;
const devServerBuildOverriddenKeys: (keyof DevServerBuilderOptions)[] = [
'watch',
'optimization',
'aot',
'sourceMap',
'vendorChunk',
'commonChunk',
'baseHref',
'progress',
'poll',
'verbose',
'deployUrl',
];
// Get dev-server only options.
type DevServerOptions = Partial<
Omit<
Schema,
| 'watch'
| 'optimization'
| 'aot'
| 'sourceMap'
| 'vendorChunk'
| 'commonChunk'
| 'baseHref'
| 'progress'
| 'poll'
| 'verbose'
| 'deployUrl'
>
>;
/**
* @experimental Direct usage of this type is considered experimental.
*/
export type DevServerBuilderOutput = DevServerBuildOutput & {
baseUrl: string;
};
/**
* Reusable implementation of the Angular Webpack development server builder.
* @param options Dev Server options.
* @param context The build context.
* @param transforms A map of transforms that can be used to hook into some logic (such as
* transforming webpack configuration before passing it to webpack).
*
* @experimental Direct usage of this function is considered experimental.
*/
// eslint-disable-next-line max-lines-per-function
export function serveWebpackBrowser(
options: DevServerBuilderOptions,
context: BuilderContext,
transforms: {
webpackConfiguration?: ExecutionTransformer<webpack.Configuration>;
logging?: WebpackLoggingCallback;
indexHtml?: IndexHtmlTransform;
} = {},
): Observable<DevServerBuilderOutput> {
// Check Angular version.
const { logger, workspaceRoot } = context;
assertCompatibleAngularVersion(workspaceRoot);
const browserTarget = targetFromTargetString(options.browserTarget);
async function setup(): Promise<{
browserOptions: json.JsonObject & BrowserBuilderSchema;
webpackConfig: webpack.Configuration;
projectRoot: string;
locale: string | undefined;
}> {
// Get the browser configuration from the target name.
const rawBrowserOptions = (await context.getTargetOptions(browserTarget)) as json.JsonObject &
BrowserBuilderSchema;
options.port = await checkPort(options.port ?? 4200, options.host || 'localhost');
// Override options we need to override, if defined.
const overrides = (Object.keys(options) as (keyof DevServerBuilderOptions)[])
.filter((key) => options[key] !== undefined && devServerBuildOverriddenKeys.includes(key))
.reduce<json.JsonObject & Partial<BrowserBuilderSchema>>(
(previous, key) => ({
...previous,
[key]: options[key],
}),
{},
);
const devServerOptions: DevServerOptions = (Object.keys(options) as (keyof Schema)[])
.filter((key) => !devServerBuildOverriddenKeys.includes(key) && key !== 'browserTarget')
.reduce<DevServerOptions>(
(previous, key) => ({
...previous,
[key]: options[key],
}),
{},
);
// In dev server we should not have budgets because of extra libs such as socks-js
overrides.budgets = undefined;
if (rawBrowserOptions.outputHashing && rawBrowserOptions.outputHashing !== OutputHashing.None) {
// Disable output hashing for dev build as this can cause memory leaks
// See: https://github.com/webpack/webpack-dev-server/issues/377#issuecomment-241258405
overrides.outputHashing = OutputHashing.None;
logger.warn(`Warning: 'outputHashing' option is disabled when using the dev-server.`);
}
if (options.hmr) {
logger.warn(tags.stripIndents`NOTICE: Hot Module Replacement (HMR) is enabled for the dev server.
See https://webpack.js.org/guides/hot-module-replacement for information on working with HMR for Webpack.`);
}
if (
!options.disableHostCheck &&
options.host &&
!/^127\.\d+\.\d+\.\d+/g.test(options.host) &&
options.host !== 'localhost'
) {
logger.warn(tags.stripIndent`
Warning: This is a simple server for use in testing or debugging Angular applications
locally. It hasn't been reviewed for security issues.
Binding this server to an open connection can result in compromising your application or
computer. Using a different host than the one passed to the "--host" flag might result in
websocket connection issues. You might need to use "--disable-host-check" if that's the
case.
`);
}
if (options.disableHostCheck) {
logger.warn(tags.oneLine`
Warning: Running a server with --disable-host-check is a security risk.
See https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a
for more information.
`);
}
// Webpack's live reload functionality adds the `strip-ansi` package which is commonJS
rawBrowserOptions.allowedCommonJsDependencies ??= [];
rawBrowserOptions.allowedCommonJsDependencies.push('strip-ansi');
const browserName = await context.getBuilderNameForTarget(browserTarget);
const browserOptions = (await context.validateOptions(
{ ...rawBrowserOptions, ...overrides },
browserName,
)) as json.JsonObject & BrowserBuilderSchema;
const { styles, scripts } = normalizeOptimization(browserOptions.optimization);
if (scripts || styles.minify) {
logger.error(tags.stripIndents`
****************************************************************************************
This is a simple server for use in testing or debugging Angular applications locally.
It hasn't been reviewed for security issues.
DON'T USE IT FOR PRODUCTION!
****************************************************************************************
`);
}
const { config, projectRoot, i18n } = await generateI18nBrowserWebpackConfigFromContext(
browserOptions,
context,
(wco) => [
getDevServerConfig(wco),
getCommonConfig(wco),
getBrowserConfig(wco),
getStylesConfig(wco),
getStatsConfig(wco),
getAnalyticsConfig(wco, context),
getTypeScriptConfig(wco),
browserOptions.webWorkerTsConfig ? getWorkerConfig(wco) : {},
],
devServerOptions,
);
if (!config.devServer) {
throw new Error('Webpack Dev Server configuration was not set.');
}
if (options.liveReload && !options.hmr) {
// This is needed because we cannot use the inline option directly in the config
// because of the SuppressExtractedTextChunksWebpackPlugin
// Consider not using SuppressExtractedTextChunksWebpackPlugin when liveReload is enable.
webpackDevServer.addDevServerEntrypoints(config, {
...config.devServer,
inline: true,
});
// Remove live-reload code from all entrypoints but not main.
// Otherwise this will break SuppressExtractedTextChunksWebpackPlugin because
// 'addDevServerEntrypoints' adds addional entry-points to all entries.
if (
config.entry &&
typeof config.entry === 'object' &&
!Array.isArray(config.entry) &&
config.entry.main
) {
for (const [key, value] of Object.entries(config.entry)) {
if (key === 'main' || !Array.isArray(value)) {
continue;
}
const webpackClientScriptIndex = value.findIndex((x) =>
x.includes('webpack-dev-server/client/index.js'),
);
if (webpackClientScriptIndex >= 0) {
// Remove the webpack-dev-server/client script from array.
value.splice(webpackClientScriptIndex, 1);
}
}
}
}
let locale: string | undefined;
if (i18n.shouldInline) {
// Dev-server only supports one locale
locale = [...i18n.inlineLocales][0];
} else if (i18n.hasDefinedSourceLocale) {
// use source locale if not localizing
locale = i18n.sourceLocale;
}
let webpackConfig = config;
// If a locale is defined, setup localization
if (locale) {
// Only supported with Ivy
const tsConfig = readTsconfig(browserOptions.tsConfig, workspaceRoot);
if (tsConfig.options.enableIvy !== false) {
if (i18n.inlineLocales.size > 1) {
throw new Error(
'The development server only supports localizing a single locale per build.',
);
}
await setupLocalize(locale, i18n, browserOptions, webpackConfig);
}
}
if (transforms.webpackConfiguration) {
webpackConfig = await transforms.webpackConfiguration(webpackConfig);
}
return {
browserOptions,
webpackConfig,
projectRoot,
locale,
};
}
return from(setup()).pipe(
switchMap(({ browserOptions, webpackConfig, projectRoot, locale }) => {
if (browserOptions.index) {
const { scripts = [], styles = [], baseHref, tsConfig } = browserOptions;
const { options: compilerOptions } = readTsconfig(tsConfig, workspaceRoot);
const target = compilerOptions.target || ts.ScriptTarget.ES5;
const buildBrowserFeatures = new BuildBrowserFeatures(projectRoot);
const entrypoints = generateEntryPoints({ scripts, styles });
const moduleEntrypoints = buildBrowserFeatures.isDifferentialLoadingNeeded(target)
? generateEntryPoints({ scripts: [], styles })
: [];
webpackConfig.plugins = [...(webpackConfig.plugins || [])];
webpackConfig.plugins.push(
new IndexHtmlWebpackPlugin({
indexPath: path.resolve(workspaceRoot, getIndexInputFile(browserOptions.index)),
outputPath: getIndexOutputFile(browserOptions.index),
baseHref,
entrypoints,
moduleEntrypoints,
noModuleEntrypoints: ['polyfills-es5'],
deployUrl: browserOptions.deployUrl,
sri: browserOptions.subresourceIntegrity,
postTransform: transforms.indexHtml,
optimization: normalizeOptimization(browserOptions.optimization),
WOFFSupportNeeded: !buildBrowserFeatures.isFeatureSupported('woff2'),
crossOrigin: browserOptions.crossOrigin,
lang: locale,
}),
);
}
return runWebpackDevServer(webpackConfig, context, {
logging: transforms.logging || createWebpackLoggingCallback(browserOptions, logger),
webpackFactory: require('webpack') as typeof webpack,
webpackDevServerFactory: require('webpack-dev-server') as typeof webpackDevServer,
}).pipe(
concatMap(async (buildEvent, index) => {
// Resolve serve address.
const serverAddress = url.format({
protocol: options.ssl ? 'https' : 'http',
hostname: options.host === '0.0.0.0' ? 'localhost' : options.host,
pathname: webpackConfig.devServer?.publicPath,
port: buildEvent.port,
});
if (index === 0) {
logger.info(
'\n' +
tags.oneLine`
**
Angular Live Development Server is listening on ${options.host}:${buildEvent.port},
open your browser on ${serverAddress}
**
` +
'\n',
);
if (options.open) {
const open = (await import('open')).default;
await open(serverAddress);
}
}
if (buildEvent.success) {
logger.info(`\n${colors.greenBright(colors.symbols.check)} Compiled successfully.`);
}
return { ...buildEvent, baseUrl: serverAddress } as DevServerBuilderOutput;
}),
);
}),
);
}
async function setupLocalize(
locale: string,
i18n: I18nOptions,
browserOptions: BrowserBuilderSchema,
webpackConfig: webpack.Configuration,
) {
const localeDescription = i18n.locales[locale];
// Modify main entrypoint to include locale data
if (
localeDescription?.dataPath &&
typeof webpackConfig.entry === 'object' &&
!Array.isArray(webpackConfig.entry) &&
webpackConfig.entry['main']
) {
if (Array.isArray(webpackConfig.entry['main'])) {
webpackConfig.entry['main'].unshift(localeDescription.dataPath);
} else {
webpackConfig.entry['main'] = [
localeDescription.dataPath,
webpackConfig.entry['main'] as string,
];
}
}
let missingTranslationBehavior = browserOptions.i18nMissingTranslation || 'ignore';
let translation = localeDescription?.translation || {};
if (locale === i18n.sourceLocale) {
missingTranslationBehavior = 'ignore';
translation = {};
}
const i18nLoaderOptions = {
locale,
missingTranslationBehavior,
translation: i18n.shouldInline ? translation : undefined,
};
const i18nRule: webpack.RuleSetRule = {
test: /\.(?:[cm]?js|ts)$/,
enforce: 'post',
use: [
{
loader: require.resolve('../babel/webpack-loader'),
options: {
cacheDirectory: findCachePath('babel-dev-server-i18n'),
cacheIdentifier: JSON.stringify({
locale,
translationIntegrity: localeDescription?.files.map((file) => file.integrity),
}),
i18n: i18nLoaderOptions,
},
},
],
};
// Get the rules and ensure the Webpack configuration is setup properly
const rules = webpackConfig.module?.rules || [];
if (!webpackConfig.module) {
webpackConfig.module = { rules };
} else if (!webpackConfig.module.rules) {
webpackConfig.module.rules = rules;
}
rules.push(i18nRule);
}
export default createBuilder<DevServerBuilderOptions, DevServerBuilderOutput>(serveWebpackBrowser);