-
Notifications
You must be signed in to change notification settings - Fork 12k
/
Copy pathcommon.ts
314 lines (280 loc) · 10 KB
/
common.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
/**
* @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 * as CopyWebpackPlugin from 'copy-webpack-plugin';
import * as path from 'path';
import { HashedModuleIdsPlugin, debug } from 'webpack';
import { AssetPatternObject } from '../../../browser/schema';
import { BundleBudgetPlugin } from '../../plugins/bundle-budget';
import { CleanCssWebpackPlugin } from '../../plugins/cleancss-webpack-plugin';
import { ScriptsWebpackPlugin } from '../../plugins/scripts-webpack-plugin';
import { findUp } from '../../utilities/find-up';
import { isDirectory } from '../../utilities/is-directory';
import { requireProjectModule } from '../../utilities/require-project-module';
import { WebpackConfigOptions } from '../build-options';
import { getOutputHashFormat, normalizeExtraEntryPoints } from './utils';
const ProgressPlugin = require('webpack/lib/ProgressPlugin');
const CircularDependencyPlugin = require('circular-dependency-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const StatsPlugin = require('stats-webpack-plugin');
// tslint:disable-next-line:no-any
const g: any = typeof global !== 'undefined' ? global : {};
export const buildOptimizerLoader: string = g['_DevKitIsLocal']
? require.resolve('@angular-devkit/build-optimizer/src/build-optimizer/webpack-loader')
: '@angular-devkit/build-optimizer/webpack-loader';
// tslint:disable-next-line:no-big-function
export function getCommonConfig(wco: WebpackConfigOptions) {
const { root, projectRoot, buildOptions } = wco;
const nodeModules = findUp('node_modules', projectRoot);
if (!nodeModules) {
throw new Error('Cannot locate node_modules directory.');
}
// tslint:disable-next-line:no-any
const extraPlugins: any[] = [];
const entryPoints: { [key: string]: string[] } = {};
if (buildOptions.main) {
entryPoints['main'] = [path.resolve(root, buildOptions.main)];
}
if (buildOptions.polyfills) {
entryPoints['polyfills'] = [path.resolve(root, buildOptions.polyfills)];
}
if (!buildOptions.aot) {
entryPoints['polyfills'] = [
...(entryPoints['polyfills'] || []),
path.join(__dirname, '..', 'jit-polyfills.js'),
];
}
if (buildOptions.profile) {
extraPlugins.push(new debug.ProfilingPlugin({
outputPath: path.resolve(root, 'chrome-profiler-events.json'),
}));
}
// determine hashing format
const hashFormat = getOutputHashFormat(buildOptions.outputHashing || 'none');
// process global scripts
if (buildOptions.scripts.length > 0) {
const globalScriptsByBundleName = normalizeExtraEntryPoints(buildOptions.scripts, 'scripts')
.reduce((prev: { bundleName: string, paths: string[], lazy: boolean }[], curr) => {
const bundleName = curr.bundleName;
const resolvedPath = path.resolve(root, curr.input);
const existingEntry = prev.find((el) => el.bundleName === bundleName);
if (existingEntry) {
if (existingEntry.lazy && !curr.lazy) {
// All entries have to be lazy for the bundle to be lazy.
throw new Error(`The ${curr.bundleName} bundle is mixing lazy and non-lazy scripts.`);
}
existingEntry.paths.push(resolvedPath);
} else {
prev.push({
bundleName,
paths: [resolvedPath],
lazy: curr.lazy,
});
}
return prev;
}, []);
// Add a new asset for each entry.
globalScriptsByBundleName.forEach((script) => {
// Lazy scripts don't get a hash, otherwise they can't be loaded by name.
const hash = script.lazy ? '' : hashFormat.script;
const bundleName = script.bundleName;
extraPlugins.push(new ScriptsWebpackPlugin({
name: bundleName,
sourceMap: buildOptions.sourceMap,
filename: `${path.basename(bundleName)}${hash}.js`,
scripts: script.paths,
basePath: projectRoot,
}));
});
}
// process asset entries
if (buildOptions.assets) {
const copyWebpackPluginPatterns = buildOptions.assets.map((asset: AssetPatternObject) => {
// Resolve input paths relative to workspace root and add slash at the end.
asset.input = path.resolve(root, asset.input).replace(/\\/g, '/');
asset.input = asset.input.endsWith('/') ? asset.input : asset.input + '/';
asset.output = asset.output.endsWith('/') ? asset.output : asset.output + '/';
if (asset.output.startsWith('..')) {
const message = 'An asset cannot be written to a location outside of the output path.';
throw new Error(message);
}
return {
context: asset.input,
// Now we remove starting slash to make Webpack place it from the output root.
to: asset.output.replace(/^\//, ''),
ignore: asset.ignore,
from: {
glob: asset.glob,
dot: true,
},
};
});
const copyWebpackPluginOptions = { ignore: ['.gitkeep', '**/.DS_Store', '**/Thumbs.db'] };
const copyWebpackPluginInstance = new CopyWebpackPlugin(copyWebpackPluginPatterns,
copyWebpackPluginOptions);
extraPlugins.push(copyWebpackPluginInstance);
}
if (buildOptions.progress) {
extraPlugins.push(new ProgressPlugin({ profile: buildOptions.verbose, colors: true }));
}
if (buildOptions.showCircularDependencies) {
extraPlugins.push(new CircularDependencyPlugin({
exclude: /[\\\/]node_modules[\\\/]/,
}));
}
if (buildOptions.statsJson) {
extraPlugins.push(new StatsPlugin('stats.json', 'verbose'));
}
let sourceMapUseRule;
if (buildOptions.sourceMap && buildOptions.vendorSourceMap) {
sourceMapUseRule = {
use: [
{
loader: 'source-map-loader',
},
],
};
}
let buildOptimizerUseRule;
if (buildOptions.buildOptimizer) {
buildOptimizerUseRule = {
use: [
{
loader: buildOptimizerLoader,
options: { sourceMap: buildOptions.sourceMap },
},
],
};
}
// Allow loaders to be in a node_modules nested inside the devkit/build-angular package.
// This is important in case loaders do not get hoisted.
// If this file moves to another location, alter potentialNodeModules as well.
const loaderNodeModules = ['node_modules'];
const buildAngularNodeModules = findUp('node_modules', __dirname);
if (buildAngularNodeModules
&& isDirectory(buildAngularNodeModules)
&& buildAngularNodeModules !== nodeModules
&& buildAngularNodeModules.startsWith(nodeModules)
) {
loaderNodeModules.push(buildAngularNodeModules);
}
// Load rxjs path aliases.
// https://github.com/ReactiveX/rxjs/blob/master/doc/lettable-operators.md#build-and-treeshaking
let alias = {};
try {
const rxjsPathMappingImport = wco.supportES2015
? 'rxjs/_esm2015/path-mapping'
: 'rxjs/_esm5/path-mapping';
const rxPaths = requireProjectModule(projectRoot, rxjsPathMappingImport);
alias = rxPaths(nodeModules);
} catch { }
const terserOptions = {
ecma: wco.supportES2015 ? 6 : 5,
warnings: !!buildOptions.verbose,
safari10: true,
output: {
ascii_only: true,
comments: false,
webkit: true,
},
// On server, we don't want to compress anything. We still set the ngDevMode = false for it
// to remove dev code.
compress: (buildOptions.platform == 'server' ? {
global_defs: {
ngDevMode: false,
},
} : {
pure_getters: buildOptions.buildOptimizer,
// PURE comments work best with 3 passes.
// See https://github.com/webpack/webpack/issues/2899#issuecomment-317425926.
passes: buildOptions.buildOptimizer ? 3 : 1,
global_defs: {
ngDevMode: false,
},
}),
// We also want to avoid mangling on server.
...(buildOptions.platform == 'server' ? { mangle: false } : {}),
};
return {
mode: buildOptions.optimization ? 'production' : 'development',
devtool: false,
resolve: {
extensions: ['.ts', '.tsx', '.mjs', '.js'],
symlinks: !buildOptions.preserveSymlinks,
modules: [
wco.tsConfig.options.baseUrl || projectRoot,
'node_modules',
],
alias,
},
resolveLoader: {
modules: loaderNodeModules,
},
context: projectRoot,
entry: entryPoints,
output: {
path: path.resolve(root, buildOptions.outputPath as string),
publicPath: buildOptions.deployUrl,
filename: `[name]${hashFormat.chunk}.js`,
},
watch: buildOptions.watch,
watchOptions: {
poll: buildOptions.poll,
},
performance: {
hints: false,
},
module: {
rules: [
{ test: /\.html$/, loader: 'raw-loader' },
{
test: /\.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)$/,
loader: 'file-loader',
options: {
name: `[name]${hashFormat.file}.[ext]`,
},
},
{
// Mark files inside `@angular/core` as using SystemJS style dynamic imports.
// Removing this will cause deprecation warnings to appear.
test: /[\/\\]@angular[\/\\]core[\/\\].+\.js$/,
parser: { system: true },
},
{
test: /\.js$/,
...buildOptimizerUseRule,
},
{
test: /\.js$/,
exclude: /(ngfactory|ngstyle).js$/,
enforce: 'pre',
...sourceMapUseRule,
},
],
},
optimization: {
noEmitOnErrors: true,
minimizer: [
new HashedModuleIdsPlugin(),
// TODO: check with Mike what this feature needs.
new BundleBudgetPlugin({ budgets: buildOptions.budgets }),
new CleanCssWebpackPlugin({
sourceMap: buildOptions.sourceMap,
// component styles retain their original file name
test: (file) => /\.(?:css|scss|sass|less|styl)$/.test(file),
}),
new TerserPlugin({
sourceMap: buildOptions.sourceMap,
parallel: true,
cache: true,
terserOptions,
}),
],
},
plugins: extraPlugins,
};
}