-
Notifications
You must be signed in to change notification settings - Fork 12k
/
Copy pathwebpack-browser-config.ts
254 lines (229 loc) · 8.22 KB
/
webpack-browser-config.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
/**
* @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 } from '@angular-devkit/architect';
import {
getSystemPath,
logging,
normalize,
resolve,
virtualFs,
} from '@angular-devkit/core';
import { NodeJsSyncHost } from '@angular-devkit/core/node';
import * as fs from 'fs';
import * as path from 'path';
import * as webpack from 'webpack';
import { merge as webpackMerge } from 'webpack-merge';
import { Schema as BrowserBuilderSchema } from '../browser/schema';
import {
NormalizedBrowserBuilderSchema,
defaultProgress,
normalizeBrowserSchema,
} from '../utils';
import { WebpackConfigOptions } from '../utils/build-options';
import { readTsconfig } from '../utils/read-tsconfig';
import { getEsVersionForFileName } from '../webpack/utils/helpers';
import { profilingEnabled } from './environment-options';
import { I18nOptions, configureI18nBuild } from './i18n-options';
export type BrowserWebpackConfigOptions = WebpackConfigOptions<NormalizedBrowserBuilderSchema>;
export async function generateWebpackConfig(
workspaceRoot: string,
projectRoot: string,
sourceRoot: string | undefined,
options: NormalizedBrowserBuilderSchema,
webpackPartialGenerator: (wco: BrowserWebpackConfigOptions) => webpack.Configuration[],
logger: logging.LoggerApi,
differentialLoadingMode: boolean,
): Promise<webpack.Configuration> {
// Ensure Build Optimizer is only used with AOT.
if (options.buildOptimizer && !options.aot) {
throw new Error(`The 'buildOptimizer' option cannot be used without 'aot'.`);
}
// Ensure Rollup Concatenation is only used with compatible options.
if (options.experimentalRollupPass) {
if (!options.aot) {
throw new Error(`The 'experimentalRollupPass' option cannot be used without 'aot'.`);
}
if (options.vendorChunk || options.commonChunk || options.namedChunks) {
throw new Error(`The 'experimentalRollupPass' option cannot be used with the`
+ `'vendorChunk', 'commonChunk', 'namedChunks' options set to true.`);
}
}
const tsConfigPath = path.resolve(workspaceRoot, options.tsConfig);
const tsConfig = readTsconfig(tsConfigPath);
// tslint:disable-next-line:no-implicit-dependencies
const ts = await import('typescript');
const scriptTarget = tsConfig.options.target || ts.ScriptTarget.ES5;
const supportES2015 = scriptTarget !== ts.ScriptTarget.JSON && scriptTarget > ts.ScriptTarget.ES5;
const buildOptions: NormalizedBrowserBuilderSchema = { ...options };
const wco: BrowserWebpackConfigOptions = {
root: workspaceRoot,
logger: logger.createChild('webpackConfigOptions'),
projectRoot,
sourceRoot,
buildOptions,
tsConfig,
tsConfigPath,
supportES2015,
differentialLoadingMode,
};
wco.buildOptions.progress = defaultProgress(wco.buildOptions.progress);
const webpackConfig = webpackMerge(webpackPartialGenerator(wco));
if (supportES2015) {
if (!webpackConfig.resolve) {
webpackConfig.resolve = {};
}
if (Array.isArray(webpackConfig.resolve.alias)) {
webpackConfig.resolve.alias.push({
alias: 'zone.js/dist/zone',
name: 'zone.js/dist/zone-evergreen',
});
} else {
if (!webpackConfig.resolve.alias) {
webpackConfig.resolve.alias = {};
}
webpackConfig.resolve.alias['zone.js/dist/zone'] = 'zone.js/dist/zone-evergreen';
}
}
if (profilingEnabled) {
const esVersionInFileName = getEsVersionForFileName(
tsConfig.options.target,
wco.differentialLoadingMode,
);
const SpeedMeasurePlugin = await import('speed-measure-webpack-plugin');
const smp = new SpeedMeasurePlugin({
outputFormat: 'json',
outputTarget: path.resolve(
workspaceRoot,
`speed-measure-plugin${esVersionInFileName}.json`,
),
});
return smp.wrap(webpackConfig);
}
return webpackConfig;
}
export async function generateI18nBrowserWebpackConfigFromContext(
options: BrowserBuilderSchema,
context: BuilderContext,
webpackPartialGenerator: (wco: BrowserWebpackConfigOptions) => webpack.Configuration[],
host: virtualFs.Host<fs.Stats> = new NodeJsSyncHost(),
differentialLoadingMode = false,
): Promise<{ config: webpack.Configuration; projectRoot: string; projectSourceRoot?: string, i18n: I18nOptions }> {
const { buildOptions, i18n } = await configureI18nBuild(context, options);
const result = await generateBrowserWebpackConfigFromContext(
buildOptions,
context,
webpackPartialGenerator,
host,
differentialLoadingMode,
);
const config = result.config;
if (i18n.shouldInline) {
// Remove localize "polyfill" if in AOT mode
if (buildOptions.aot) {
if (!config.resolve) {
config.resolve = {};
}
if (Array.isArray(config.resolve.alias)) {
config.resolve.alias.push({
alias: '@angular/localize/init',
name: require.resolve('./empty.js'),
});
} else {
if (!config.resolve.alias) {
config.resolve.alias = {};
}
config.resolve.alias['@angular/localize/init'] = require.resolve('./empty.js');
}
}
// Update file hashes to include translation file content
const i18nHash = Object.values(i18n.locales).reduce(
(data, locale) => data + locale.files.map((file) => file.integrity || '').join('|'),
'',
);
if (!config.plugins) {
config.plugins = [];
}
config.plugins.push({
apply(compiler: webpack.Compiler) {
compiler.hooks.compilation.tap('build-angular', compilation => {
// Webpack typings do not contain template hashForChunk hook
// tslint:disable-next-line: no-any
(compilation.mainTemplate.hooks as any).hashForChunk.tap(
'build-angular',
(hash: { update(data: string): void }) => {
hash.update('$localize' + i18nHash);
},
);
// Webpack typings do not contain hooks property
// tslint:disable-next-line: no-any
(compilation.chunkTemplate as any).hooks.hashForChunk.tap(
'build-angular',
(hash: { update(data: string): void }) => {
hash.update('$localize' + i18nHash);
},
);
});
},
});
}
return { ...result, i18n };
}
export async function generateBrowserWebpackConfigFromContext(
options: BrowserBuilderSchema,
context: BuilderContext,
webpackPartialGenerator: (wco: BrowserWebpackConfigOptions) => webpack.Configuration[],
host: virtualFs.Host<fs.Stats> = new NodeJsSyncHost(),
differentialLoadingMode = false,
): Promise<{ config: webpack.Configuration; projectRoot: string; projectSourceRoot?: string }> {
const projectName = context.target && context.target.project;
if (!projectName) {
throw new Error('The builder requires a target.');
}
const workspaceRoot = normalize(context.workspaceRoot);
const projectMetadata = await context.getProjectMetadata(projectName);
const projectRoot = resolve(workspaceRoot, normalize((projectMetadata.root as string) || ''));
const projectSourceRoot = projectMetadata.sourceRoot as string | undefined;
const sourceRoot = projectSourceRoot
? resolve(workspaceRoot, normalize(projectSourceRoot))
: undefined;
const normalizedOptions = normalizeBrowserSchema(
host,
workspaceRoot,
projectRoot,
sourceRoot,
options,
);
const config = await generateWebpackConfig(
getSystemPath(workspaceRoot),
getSystemPath(projectRoot),
sourceRoot && getSystemPath(sourceRoot),
normalizedOptions,
webpackPartialGenerator,
context.logger,
differentialLoadingMode,
);
return {
config,
projectRoot: getSystemPath(projectRoot),
projectSourceRoot: sourceRoot && getSystemPath(sourceRoot),
};
}
export function getIndexOutputFile(options: BrowserBuilderSchema): string {
if (typeof options.index === 'string') {
return path.basename(options.index);
} else {
return options.index.output || 'index.html';
}
}
export function getIndexInputFile(options: BrowserBuilderSchema): string {
if (typeof options.index === 'string') {
return options.index;
} else {
return options.index.input;
}
}