Angular v17构建:自定义子资源完整性算法(替换SHA384为SHA256)
解决方案:Angular 17 替换Subresource Integrity算法为SHA256
方案1:自定义Webpack配置覆盖默认插件参数
Angular 17开启subresourceIntegrity: true时,会自动引入webpack-subresource-integrity插件但默认使用SHA384。我们可以通过自定义Webpack配置修改已有插件的算法配置:
- 安装自定义Webpack构建工具:
npm install @angular-builders/custom-webpack --save-dev
- 修改
angular.json的构建配置,切换为自定义Webpack构建器:
"architect": { "build": { "builder": "@angular-builders/custom-webpack:browser", "options": { "customWebpackConfig": { "path": "./webpack.config.js" }, "subresourceIntegrity": true, // 保留原有其他配置 } } }
- 在项目根目录创建
webpack.config.js,添加代码修改插件参数:
module.exports = { plugins: [ { apply: (compiler) => { compiler.hooks.compilation.tap('ModifySRIPlugin', () => { // 找到已加载的subresource-integrity插件实例 const sriPlugin = compiler.options.plugins.find( plugin => plugin.constructor.name === 'SubresourceIntegrityPlugin' ); if (sriPlugin) { // 替换哈希算法为SHA256 sriPlugin.options.hashFuncNames = ['sha256']; } }); } } ] };
方案2:禁用Angular自带SRI,手动配置插件
如果方案1不生效,可完全禁用Angular自带的SRI逻辑,手动配置插件:
按方案1步骤1-2配置自定义Webpack构建器,同时修改
angular.json设置subresourceIntegrity: false。安装
webpack-subresource-integrity插件:
npm install webpack-subresource-integrity --save-dev
- 修改
webpack.config.js,手动引入并配置插件:
const SubresourceIntegrityPlugin = require('webpack-subresource-integrity'); module.exports = { output: { // 必须启用该配置,否则SRI属性无法正常生成 crossOriginLoading: 'anonymous' }, plugins: [ new SubresourceIntegrityPlugin({ hashFuncNames: ['sha256'] }) ] };
方案3:Post-build脚本批量修改index.html
若Webpack配置方式有障碍,可通过Node.js脚本在构建完成后,重新计算SHA256哈希并替换原有SRI属性:
- 在项目根目录创建
fix-sri.js:
const fs = require('fs'); const path = require('path'); const crypto = require('crypto'); // 替换为你的项目dist目录路径 const distPath = path.join(__dirname, 'dist', 'your-project-name'); const indexPath = path.join(distPath, 'index.html'); let indexContent = fs.readFileSync(indexPath, 'utf8'); // 匹配所有带SHA384 integrity属性的script标签 const scriptRegex = /<script.*integrity="sha384-[^"]+".*>/g; indexContent = indexContent.replace(scriptRegex, (match) => { // 提取script的src路径 const srcMatch = match.match(/src="([^"]+)"/); if (!srcMatch) return match; const scriptFilePath = path.join(distPath, srcMatch[1]); if (!fs.existsSync(scriptFilePath)) return match; // 计算文件的SHA256哈希 const fileContent = fs.readFileSync(scriptFilePath); const hashBase64 = crypto.createHash('sha256').update(fileContent).digest('base64'); const newIntegrity = `sha256-${hashBase64}`; // 替换原有integrity属性 return match.replace(/integrity="sha384-[^"]+"/, `integrity="${newIntegrity}"`); }); // 写回修改后的index.html fs.writeFileSync(indexPath, indexContent); console.log('SRI算法已替换为SHA256');
- 修改
package.json的scripts,添加构建后执行脚本的命令:
"scripts": { "build": "ng build", "postbuild": "node fix-sri.js" }
- 执行
npm run build,构建完成后脚本会自动处理index.html中的SRI属性。
内容的提问来源于stack exchange,提问作者Wayne Kaskie
相关产品推荐
相关产品推荐

