source: trip-planner-front/node_modules/@angular-devkit/build-angular/src/webpack/configs/common.js@ 8d391a1

Last change on this file since 8d391a1 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 21.1 KB
Line 
1"use strict";
2/**
3 * @license
4 * Copyright Google LLC All Rights Reserved.
5 *
6 * Use of this source code is governed by an MIT-style license that can be
7 * found in the LICENSE file at https://angular.io/license
8 */
9var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10 if (k2 === undefined) k2 = k;
11 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
12}) : (function(o, m, k, k2) {
13 if (k2 === undefined) k2 = k;
14 o[k2] = m[k];
15}));
16var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
17 Object.defineProperty(o, "default", { enumerable: true, value: v });
18}) : function(o, v) {
19 o["default"] = v;
20});
21var __importStar = (this && this.__importStar) || function (mod) {
22 if (mod && mod.__esModule) return mod;
23 var result = {};
24 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
25 __setModuleDefault(result, mod);
26 return result;
27};
28var __importDefault = (this && this.__importDefault) || function (mod) {
29 return (mod && mod.__esModule) ? mod : { "default": mod };
30};
31Object.defineProperty(exports, "__esModule", { value: true });
32exports.getCommonConfig = void 0;
33const build_optimizer_1 = require("@angular-devkit/build-optimizer");
34const compiler_cli_1 = require("@angular/compiler-cli");
35const copy_webpack_plugin_1 = __importDefault(require("copy-webpack-plugin"));
36const crypto_1 = require("crypto");
37const fs_1 = require("fs");
38const path = __importStar(require("path"));
39const typescript_1 = require("typescript");
40const webpack_1 = require("webpack");
41const utils_1 = require("../../utils");
42const cache_path_1 = require("../../utils/cache-path");
43const environment_options_1 = require("../../utils/environment-options");
44const find_up_1 = require("../../utils/find-up");
45const spinner_1 = require("../../utils/spinner");
46const webpack_diagnostics_1 = require("../../utils/webpack-diagnostics");
47const plugins_1 = require("../plugins");
48const javascript_optimizer_plugin_1 = require("../plugins/javascript-optimizer-plugin");
49const helpers_1 = require("../utils/helpers");
50// eslint-disable-next-line max-lines-per-function
51function getCommonConfig(wco) {
52 var _a, _b;
53 const { root, projectRoot, buildOptions, tsConfig } = wco;
54 const { platform = 'browser', sourceMap: { styles: stylesSourceMap, scripts: scriptsSourceMap, vendor: vendorSourceMap }, optimization: { styles: stylesOptimization, scripts: scriptsOptimization }, } = buildOptions;
55 const extraPlugins = [];
56 const extraRules = [];
57 const entryPoints = {};
58 // determine hashing format
59 const hashFormat = helpers_1.getOutputHashFormat(buildOptions.outputHashing || 'none');
60 const buildBrowserFeatures = new utils_1.BuildBrowserFeatures(projectRoot);
61 const targetInFileName = helpers_1.getEsVersionForFileName(tsConfig.options.target, buildOptions.differentialLoadingNeeded);
62 if (buildOptions.progress) {
63 const spinner = new spinner_1.Spinner();
64 spinner.start(`Generating ${platform} application bundles (phase: setup)...`);
65 extraPlugins.push(new webpack_1.ProgressPlugin({
66 handler: (percentage, message) => {
67 const phase = message ? ` (phase: ${message})` : '';
68 spinner.text = `Generating ${platform} application bundles${phase}...`;
69 switch (percentage) {
70 case 1:
71 if (spinner.isSpinning) {
72 spinner.succeed(`${platform.replace(/^\w/, (s) => s.toUpperCase())} application bundle generation complete.`);
73 }
74 break;
75 case 0:
76 if (!spinner.isSpinning) {
77 spinner.start();
78 }
79 break;
80 }
81 },
82 }));
83 }
84 if (buildOptions.main) {
85 const mainPath = path.resolve(root, buildOptions.main);
86 entryPoints['main'] = [mainPath];
87 }
88 const differentialLoadingMode = buildOptions.differentialLoadingNeeded && !buildOptions.watch;
89 if (platform !== 'server') {
90 if (differentialLoadingMode || tsConfig.options.target === typescript_1.ScriptTarget.ES5) {
91 if (buildBrowserFeatures.isEs5SupportNeeded()) {
92 const polyfillsChunkName = 'polyfills-es5';
93 entryPoints[polyfillsChunkName] = [path.join(__dirname, '..', 'es5-polyfills.js')];
94 if (!buildOptions.aot) {
95 if (differentialLoadingMode) {
96 entryPoints[polyfillsChunkName].push(path.join(__dirname, '..', 'jit-polyfills.js'));
97 }
98 entryPoints[polyfillsChunkName].push(path.join(__dirname, '..', 'es5-jit-polyfills.js'));
99 }
100 // If not performing a full differential build the polyfills need to be added to ES5 bundle
101 if (buildOptions.polyfills) {
102 entryPoints[polyfillsChunkName].push(path.resolve(root, buildOptions.polyfills));
103 }
104 }
105 }
106 if (buildOptions.polyfills) {
107 const projectPolyfills = path.resolve(root, buildOptions.polyfills);
108 if (entryPoints['polyfills']) {
109 entryPoints['polyfills'].push(projectPolyfills);
110 }
111 else {
112 entryPoints['polyfills'] = [projectPolyfills];
113 }
114 }
115 if (!buildOptions.aot) {
116 const jitPolyfills = path.join(__dirname, '..', 'jit-polyfills.js');
117 if (entryPoints['polyfills']) {
118 entryPoints['polyfills'].push(jitPolyfills);
119 }
120 else {
121 entryPoints['polyfills'] = [jitPolyfills];
122 }
123 }
124 }
125 if (environment_options_1.profilingEnabled) {
126 extraPlugins.push(new webpack_1.debug.ProfilingPlugin({
127 outputPath: path.resolve(root, 'chrome-profiler-events.json'),
128 }));
129 }
130 // process global scripts
131 const globalScriptsByBundleName = helpers_1.normalizeExtraEntryPoints(buildOptions.scripts, 'scripts').reduce((prev, curr) => {
132 const { bundleName, inject, input } = curr;
133 let resolvedPath = path.resolve(root, input);
134 if (!fs_1.existsSync(resolvedPath)) {
135 try {
136 resolvedPath = require.resolve(input, { paths: [root] });
137 }
138 catch {
139 throw new Error(`Script file ${input} does not exist.`);
140 }
141 }
142 const existingEntry = prev.find((el) => el.bundleName === bundleName);
143 if (existingEntry) {
144 if (existingEntry.inject && !inject) {
145 // All entries have to be lazy for the bundle to be lazy.
146 throw new Error(`The ${bundleName} bundle is mixing injected and non-injected scripts.`);
147 }
148 existingEntry.paths.push(resolvedPath);
149 }
150 else {
151 prev.push({
152 bundleName,
153 inject,
154 paths: [resolvedPath],
155 });
156 }
157 return prev;
158 }, []);
159 // Add a new asset for each entry.
160 for (const script of globalScriptsByBundleName) {
161 // Lazy scripts don't get a hash, otherwise they can't be loaded by name.
162 const hash = script.inject ? hashFormat.script : '';
163 const bundleName = script.bundleName;
164 extraPlugins.push(new plugins_1.ScriptsWebpackPlugin({
165 name: bundleName,
166 sourceMap: scriptsSourceMap,
167 filename: `${path.basename(bundleName)}${hash}.js`,
168 scripts: script.paths,
169 basePath: projectRoot,
170 }));
171 }
172 // process asset entries
173 if (buildOptions.assets.length) {
174 const copyWebpackPluginPatterns = buildOptions.assets.map((asset, index) => {
175 // Resolve input paths relative to workspace root and add slash at the end.
176 // eslint-disable-next-line prefer-const
177 let { input, output, ignore = [], glob } = asset;
178 input = path.resolve(root, input).replace(/\\/g, '/');
179 input = input.endsWith('/') ? input : input + '/';
180 output = output.endsWith('/') ? output : output + '/';
181 if (output.startsWith('..')) {
182 throw new Error('An asset cannot be written to a location outside of the output path.');
183 }
184 return {
185 context: input,
186 // Now we remove starting slash to make Webpack place it from the output root.
187 to: output.replace(/^\//, ''),
188 from: glob,
189 noErrorOnMissing: true,
190 force: true,
191 globOptions: {
192 dot: true,
193 followSymbolicLinks: !!asset.followSymlinks,
194 ignore: [
195 '.gitkeep',
196 '**/.DS_Store',
197 '**/Thumbs.db',
198 // Negate patterns needs to be absolute because copy-webpack-plugin uses absolute globs which
199 // causes negate patterns not to match.
200 // See: https://github.com/webpack-contrib/copy-webpack-plugin/issues/498#issuecomment-639327909
201 ...ignore,
202 ].map((i) => path.posix.join(input, i)),
203 },
204 priority: index,
205 };
206 });
207 extraPlugins.push(new copy_webpack_plugin_1.default({
208 patterns: copyWebpackPluginPatterns,
209 }));
210 }
211 if (buildOptions.showCircularDependencies) {
212 const CircularDependencyPlugin = require('circular-dependency-plugin');
213 extraPlugins.push(new CircularDependencyPlugin({
214 exclude: /[\\\/]node_modules[\\\/]/,
215 }));
216 }
217 if (buildOptions.extractLicenses) {
218 const LicenseWebpackPlugin = require('license-webpack-plugin').LicenseWebpackPlugin;
219 extraPlugins.push(new LicenseWebpackPlugin({
220 stats: {
221 warnings: false,
222 errors: false,
223 },
224 perChunkOutput: false,
225 outputFilename: '3rdpartylicenses.txt',
226 skipChildCompilers: true,
227 }));
228 }
229 if (buildOptions.statsJson) {
230 extraPlugins.push(new (class {
231 apply(compiler) {
232 compiler.hooks.done.tapPromise('angular-cli-stats', async (stats) => {
233 const { stringifyStream } = await Promise.resolve().then(() => __importStar(require('@discoveryjs/json-ext')));
234 const data = stats.toJson('verbose');
235 const statsOutputPath = path.resolve(root, buildOptions.outputPath, 'stats.json');
236 try {
237 await fs_1.promises.mkdir(path.dirname(statsOutputPath), { recursive: true });
238 await new Promise((resolve, reject) => stringifyStream(data)
239 .pipe(fs_1.createWriteStream(statsOutputPath))
240 .on('close', resolve)
241 .on('error', reject));
242 }
243 catch (error) {
244 webpack_diagnostics_1.addError(stats.compilation, `Unable to write stats file: ${error.message || 'unknown error'}`);
245 }
246 });
247 }
248 })());
249 }
250 if (scriptsSourceMap || stylesSourceMap) {
251 extraRules.push({
252 test: /\.m?js$/,
253 enforce: 'pre',
254 loader: require.resolve('source-map-loader'),
255 options: {
256 filterSourceMappingUrl: (_mapUri, resourcePath) => {
257 if (vendorSourceMap) {
258 // Consume all sourcemaps when vendor option is enabled.
259 return true;
260 }
261 // Don't consume sourcemaps in node_modules when vendor is disabled.
262 // But, do consume local libraries sourcemaps.
263 return !resourcePath.includes('node_modules');
264 },
265 },
266 });
267 }
268 let buildOptimizerUseRule = [];
269 if (buildOptions.buildOptimizer && wco.scriptTarget < typescript_1.ScriptTarget.ES2015) {
270 extraPlugins.push(new build_optimizer_1.BuildOptimizerWebpackPlugin());
271 buildOptimizerUseRule = [
272 {
273 loader: build_optimizer_1.buildOptimizerLoaderPath,
274 options: { sourceMap: scriptsSourceMap },
275 },
276 ];
277 }
278 const extraMinimizers = [];
279 if (scriptsOptimization) {
280 const globalScriptsNames = globalScriptsByBundleName.map((s) => s.bundleName);
281 if (globalScriptsNames.length > 0) {
282 // Script bundles are fully optimized here in one step since they are never downleveled.
283 // They are shared between ES2015 & ES5 outputs so must support ES5.
284 // The `terser-webpack-plugin` will add the minified flag to the asset which will prevent
285 // additional optimizations by the next plugin.
286 const TerserPlugin = require('terser-webpack-plugin');
287 extraMinimizers.push(new TerserPlugin({
288 parallel: environment_options_1.maxWorkers,
289 extractComments: false,
290 include: globalScriptsNames,
291 terserOptions: {
292 ecma: 5,
293 compress: environment_options_1.allowMinify,
294 output: {
295 ascii_only: true,
296 wrap_func_args: false,
297 },
298 mangle: environment_options_1.allowMangle && platform !== 'server',
299 },
300 }));
301 }
302 extraMinimizers.push(new javascript_optimizer_plugin_1.JavaScriptOptimizerPlugin({
303 define: buildOptions.aot ? compiler_cli_1.GLOBAL_DEFS_FOR_TERSER_WITH_AOT : compiler_cli_1.GLOBAL_DEFS_FOR_TERSER,
304 sourcemap: scriptsSourceMap,
305 target: wco.scriptTarget,
306 keepNames: !environment_options_1.allowMangle || platform === 'server',
307 removeLicenses: buildOptions.extractLicenses,
308 advanced: buildOptions.buildOptimizer,
309 }));
310 }
311 return {
312 mode: scriptsOptimization || stylesOptimization.minify ? 'production' : 'development',
313 devtool: false,
314 target: [
315 platform === 'server' ? 'node' : 'web',
316 tsConfig.options.target === typescript_1.ScriptTarget.ES5 ||
317 (platform !== 'server' && buildBrowserFeatures.isEs5SupportNeeded())
318 ? 'es5'
319 : 'es2015',
320 ],
321 profile: buildOptions.statsJson,
322 resolve: {
323 roots: [projectRoot],
324 extensions: ['.ts', '.tsx', '.mjs', '.js'],
325 symlinks: !buildOptions.preserveSymlinks,
326 modules: [tsConfig.options.baseUrl || projectRoot, 'node_modules'],
327 },
328 resolveLoader: {
329 symlinks: !buildOptions.preserveSymlinks,
330 modules: [
331 // Allow loaders to be in a node_modules nested inside the devkit/build-angular package.
332 // This is important in case loaders do not get hoisted.
333 // If this file moves to another location, alter potentialNodeModules as well.
334 'node_modules',
335 ...find_up_1.findAllNodeModules(__dirname, projectRoot),
336 ],
337 },
338 context: root,
339 entry: entryPoints,
340 output: {
341 clean: (_a = buildOptions.deleteOutputPath) !== null && _a !== void 0 ? _a : true,
342 path: path.resolve(root, buildOptions.outputPath),
343 publicPath: (_b = buildOptions.deployUrl) !== null && _b !== void 0 ? _b : '',
344 filename: ({ chunk }) => {
345 if ((chunk === null || chunk === void 0 ? void 0 : chunk.name) === 'polyfills-es5') {
346 return `polyfills-es5${hashFormat.chunk}.js`;
347 }
348 else {
349 return `[name]${targetInFileName}${hashFormat.chunk}.js`;
350 }
351 },
352 chunkFilename: `[name]${targetInFileName}${hashFormat.chunk}.js`,
353 },
354 watch: buildOptions.watch,
355 watchOptions: helpers_1.getWatchOptions(buildOptions.poll),
356 performance: {
357 hints: false,
358 },
359 ignoreWarnings: [
360 // Webpack 5+ has no facility to disable this warning.
361 // System.import is used in @angular/core for deprecated string-form lazy routes
362 /System.import\(\) is deprecated and will be removed soon/i,
363 // https://github.com/webpack-contrib/source-map-loader/blob/b2de4249c7431dd8432da607e08f0f65e9d64219/src/index.js#L83
364 /Failed to parse source map from/,
365 // https://github.com/webpack-contrib/postcss-loader/blob/bd261875fdf9c596af4ffb3a1a73fe3c549befda/src/index.js#L153-L158
366 /Add postcss as project dependency/,
367 ],
368 module: {
369 // Show an error for missing exports instead of a warning.
370 strictExportPresence: true,
371 rules: [
372 {
373 // Mark files inside `@angular/core` as using SystemJS style dynamic imports.
374 // Removing this will cause deprecation warnings to appear.
375 test: /[\/\\]@angular[\/\\]core[\/\\].+\.js$/,
376 parser: { system: true },
377 },
378 {
379 // Mark files inside `rxjs/add` as containing side effects.
380 // If this is fixed upstream and the fixed version becomes the minimum
381 // supported version, this can be removed.
382 test: /[\/\\]rxjs[\/\\]add[\/\\].+\.js$/,
383 sideEffects: true,
384 },
385 {
386 test: /\.[cm]?js$|\.tsx?$/,
387 // The below is needed due to a bug in `@babel/runtime`. See: https://github.com/babel/babel/issues/12824
388 resolve: { fullySpecified: false },
389 exclude: [/[/\\](?:core-js|@babel|tslib|web-animations-js|web-streams-polyfill)[/\\]/],
390 use: [
391 {
392 loader: require.resolve('../../babel/webpack-loader'),
393 options: {
394 cacheDirectory: cache_path_1.findCachePath('babel-webpack'),
395 scriptTarget: wco.scriptTarget,
396 aot: buildOptions.aot,
397 optimize: buildOptions.buildOptimizer && wco.scriptTarget >= typescript_1.ScriptTarget.ES2015,
398 },
399 },
400 ...buildOptimizerUseRule,
401 ],
402 },
403 ...extraRules,
404 ],
405 },
406 experiments: {
407 syncWebAssembly: true,
408 asyncWebAssembly: true,
409 },
410 cache: getCacheSettings(wco, buildBrowserFeatures.supportedBrowsers),
411 optimization: {
412 minimizer: extraMinimizers,
413 moduleIds: 'deterministic',
414 chunkIds: buildOptions.namedChunks ? 'named' : 'deterministic',
415 emitOnErrors: false,
416 },
417 plugins: [
418 // Always replace the context for the System.import in angular/core to prevent warnings.
419 // https://github.com/angular/angular/issues/11580
420 new webpack_1.ContextReplacementPlugin(/\@angular(\\|\/)core(\\|\/)/, path.join(projectRoot, '$_lazy_route_resources'), {}),
421 new plugins_1.DedupeModuleResolvePlugin({ verbose: buildOptions.verbose }),
422 ...extraPlugins,
423 ],
424 };
425}
426exports.getCommonConfig = getCommonConfig;
427function getCacheSettings(wco, supportedBrowsers) {
428 if (environment_options_1.persistentBuildCacheEnabled) {
429 const packageVersion = require('../../../package.json').version;
430 return {
431 type: 'filesystem',
432 cacheDirectory: cache_path_1.findCachePath('angular-webpack'),
433 maxMemoryGenerations: 1,
434 // We use the versions and build options as the cache name. The Webpack configurations are too
435 // dynamic and shared among different build types: test, build and serve.
436 // None of which are "named".
437 name: crypto_1.createHash('sha1')
438 .update(compiler_cli_1.VERSION.full)
439 .update(packageVersion)
440 .update(wco.projectRoot)
441 .update(JSON.stringify(wco.tsConfig))
442 .update(JSON.stringify({
443 ...wco.buildOptions,
444 // Needed because outputPath changes on every build when using i18n extraction
445 // https://github.com/angular/angular-cli/blob/736a5f89deaca85f487b78aec9ff66d4118ceb6a/packages/angular_devkit/build_angular/src/utils/i18n-options.ts#L264-L265
446 outputPath: undefined,
447 }))
448 .update(supportedBrowsers.join(''))
449 .digest('hex'),
450 };
451 }
452 if (wco.buildOptions.watch && !environment_options_1.cachingDisabled) {
453 return {
454 type: 'memory',
455 maxGenerations: 1,
456 };
457 }
458 return false;
459}
Note: See TracBrowser for help on using the repository browser.