[*] Удалить кодовые блоки из файлов TypeScript, которые обернуты в:
Код: Выделить всё
//#REMOVE_BLOCK_START // some code here //#REMOVE_BLOCK_END< /code> < /p>
< /li>
Удалить кодовые блоки из файлов HTML, которые обернуты в:
структура проекта
Код: Выделить всё
my-project/
├── client/ # Angular application
│ ├── angular.json
│ └── src/
└── custom-builder/ # Custom builder implementation
├── src/
│ ├── custom-builder.ts
│ ├── HtmlContentModifierPlugin.ts
│ └── remove_module.ts
├── builders.json
└── package.json
[*] Custom Builder (Custom-builder.ts):
< /ol>
import * as path from 'path';
import * as webpack from 'webpack';
import { BuilderContext, createBuilder } from '@angular-devkit/architect';
import { executeBrowserBuilder } from '@angular-devkit/build-angular';
import { HtmlContentModifierPlugin } from './HtmlContentModifierPlugin';
function transform(input: webpack.Configuration): webpack.Configuration {
if (!input.module?.rules) return input;
// Add rule for TypeScript and HTML files
// __ditname refers as 'my-project/custom-builder/dist
// (since the remove_module.ts will be converted in remove_moduel.js we are passing it in loader)
const newRule = {
test: /\.(ts|html)$/,
exclude: /node_modules/,
use: [
{
loader: path.resolve(__dirname, 'remove_module.js'),
options: {}
}
]
};
input.module.rules.unshift(newRule);
// Add HTML plugin
if (!input.plugins) {
input.plugins = [];
}
input.plugins.push(new HtmlContentModifierPlugin());
return input;
}
function executeBuilder(options: any, context: BuilderContext) {
return executeBrowserBuilder(options, context, {
webpackConfiguration: transform
});
}
export default createBuilder(executeBuilder);
< /code>
плагин HTML (htmlcontentmodifierplugin.ts): < /li>
< /ol>
import { Compiler, sources } from 'webpack';
import { Compilation } from 'webpack';
export class HtmlContentModifierPlugin {
apply(compiler: Compiler): void {
compiler.hooks.emit.tapAsync(
'HtmlContentModifierPlugin',
(compilation: Compilation, callback) => {
// Process all compiled assets
Object.keys(compilation.assets).forEach((filename) => {
if (filename.endsWith('.html')) {
console.log('Processing HTML file:', filename);
const asset = compilation.assets[filename];
const content = asset.source().toString();
// Remove assessment blocks
const modifiedContent = content.replace(
/[\s\S]*?/g,
''
);
compilation.assets[filename] = new sources.RawSource(modifiedContent);
}
});
callback();
}
);
}
}
< /code>
remove_module.ts:
< /ol>
import { LoaderDefinitionFunction } from 'webpack';
const removeAssessmentLoader: LoaderDefinitionFunction = function (source) {
const filename = this.resourcePath;
console.log("Code is running with loader for:", filename);
// Replace all occurrences of "originalText" with an empty string
if (filename.endsWith('.ts')) {
return source.replace(/\/\/#REMOVE_BLOCK_START[\s\S]*?\/\/#REMOVE_BLOCK_END/g, '');
}
// Remove HTML code between and
else if (filename.endsWith('.html')) {
console.log("HTML CHANGE");
return source.replace(/[\s\S]*?/g, '');
}
};
export default removeAssessmentLoader;
< /code>
[*]custom-builder/package.json:
< /ol>
{
"name": "custom-builder",
"version": "0.0.1",
"builders": "./builders.json",
"scripts": {
"build": "tsc"
},
"devDependencies": {
"@angular-devkit/architect": "0.1602.16",
"@angular-devkit/build-angular": "^16.2.16",
"@angular-devkit/core": "^16.2.16",
"@types/karma": "^6.3.9",
"@types/node": "~18.11.6",
"karma": "^6.4.1",
"rxjs": "~7.5.0",
"typescript": "^5.1.6"
},
"dependencies": {
"@angular-devkit/schematics": "^16.2.16",
"@angular/cli": "^16.2.16"
}
}
< /code>
configuration.json. < /li>
< /ol>
{
"projects": {
"client": {
"architect": {
"custom-target": {
"builder": "@angular-builders/custom-webpack:browser",
"options": {
"outputPath": "dist/client",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "src/tsconfig.app.json"
},
"configurations": {
"production": {
"optimization": true,
"outputHashing": "none",
"sourceMap": false,
"namedChunks": false,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true
}
}
}
}
}
}
}
< /code>
Что работает < /strong>
Обработка типовойписнойпис работает отлично. Все кодовые блоки между //#remove_block_start и //#remove_block_end успешно удалены во время сборки. работающий. Файлы HTML не обрабатываются, и кодовые блокируются между и оставаться в выходе < /p>
Вопросы < /strong> < /p>
Почему плагин HTML не обрабатывает файлы HTML? < /Li>
Есть ли лучше Подход к обработке HTML -файлов в процессе угловой сборки?
(я слышал об AngularWebpackplugin, но я не уверен, есть ли что -то похожее на преобразование для выполнения функции во время компиляции) < /li>
< / / UL>
Подробнее здесь: https://stackoverflow.com/questions/794 ... -builder-i
Мобильная версия