Skip to content

Commit

Permalink
fix(@angular-devkit/build-angular): generate different content hashes…
Browse files Browse the repository at this point in the history
… for scripts which are changed during the optimization phase

Instead of generating the content hash based on the content of scripts BEFORE the optimization phase,
the content hash is generated AFTER the optimization phase.

Prevents caching issues where browsers block execution of scripts due to the integrity hash not matching
with the cached script in case of a script being optimized differently than in a previous build,
where it would previously result in the same content hash.

Fixes #22906

(cherry picked from commit 357c45e)
  • Loading branch information
martinfrancois authored and dgp1130 committed Jul 12, 2022
1 parent 10f2449 commit 4d848c4
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ import { Chunk, Compilation, Compiler, sources as webpackSources } from 'webpack

const Entrypoint = require('webpack/lib/Entrypoint');

/**
* The name of the plugin provided to Webpack when tapping Webpack compiler hooks.
*/
const PLUGIN_NAME = 'scripts-webpack-plugin';

export interface ScriptsWebpackPluginOptions {
name: string;
sourceMap?: boolean;
Expand Down Expand Up @@ -97,8 +102,8 @@ export class ScriptsWebpackPlugin {
.filter((script) => !!script)
.map((script) => path.resolve(this.options.basePath || '', script));

compiler.hooks.thisCompilation.tap('scripts-webpack-plugin', (compilation) => {
compilation.hooks.additionalAssets.tapPromise('scripts-webpack-plugin', async () => {
compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
compilation.hooks.additionalAssets.tapPromise(PLUGIN_NAME, async () => {
if (await this.shouldSkip(compilation, scripts)) {
if (this._cachedOutput) {
this._insertOutput(compilation, this._cachedOutput, true);
Expand Down Expand Up @@ -149,19 +154,32 @@ export class ScriptsWebpackPlugin {
});

const combinedSource = new webpackSources.CachedSource(concatSource);
const filename = interpolateName(
{ resourcePath: 'scripts.js' },
this.options.filename as string,
{
content: combinedSource.source(),
},
);

const output = { filename, source: combinedSource };

const output = { filename: this.options.filename, source: combinedSource };
this._insertOutput(compilation, output);
this._cachedOutput = output;
addDependencies(compilation, scripts);
});
compilation.hooks.processAssets.tapPromise(
{
name: PLUGIN_NAME,
stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING,
},
async () => {
const assetName = this.options.filename;
const asset = compilation.getAsset(assetName);
if (asset) {
const interpolatedFilename = interpolateName(
{ resourcePath: 'scripts.js' },
assetName,
{ content: asset.source.source() },
);
if (assetName !== interpolatedFilename) {
compilation.renameAsset(assetName, interpolatedFilename);
}
}
},
);
});
}
}
45 changes: 45 additions & 0 deletions tests/legacy-cli/e2e/tests/build/scripts-output-hashing.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { expectFileMatchToExist, expectFileToMatch, writeMultipleFiles } from '../../utils/fs';
import { ng } from '../../utils/process';
import { updateJsonFile, updateTsConfig } from '../../utils/project';

function getScriptsFilename(): Promise<string> {
return expectFileMatchToExist('dist/test-project/', /external-module\.[0-9a-f]{16}\.js/);
}

export default async function () {
// verify content hash is based on code after optimizations
await writeMultipleFiles({
'src/script.js': 'try { console.log(); } catch {}',
});
await updateJsonFile('angular.json', (configJson) => {
const build = configJson.projects['test-project'].architect.build;
build.options['scripts'] = [
{
input: 'src/script.js',
inject: true,
bundleName: 'external-module',
},
];
build.configurations['production'].outputHashing = 'all';
configJson['cli'] = { cache: { enabled: 'false' } };
});
await updateTsConfig((json) => {
json['compilerOptions']['target'] = 'es2017';
json['compilerOptions']['module'] = 'es2020';
});
await ng('build', '--configuration=production');
const filenameBuild1 = await getScriptsFilename();
await expectFileToMatch(`dist/test-project/${filenameBuild1}`, 'try{console.log()}catch(c){}');

await updateTsConfig((json) => {
json['compilerOptions']['target'] = 'es2019';
});
await ng('build', '--configuration=production');
const filenameBuild2 = await getScriptsFilename();
await expectFileToMatch(`dist/test-project/${filenameBuild2}`, 'try{console.log()}catch{}');
if (filenameBuild1 === filenameBuild2) {
throw new Error(
'Contents of the built file changed between builds, but the content hash stayed the same!',
);
}
}

0 comments on commit 4d848c4

Please sign in to comment.