-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbabel-plugin-remove-code-between-comments.js
More file actions
54 lines (48 loc) · 1.68 KB
/
babel-plugin-remove-code-between-comments.js
File metadata and controls
54 lines (48 loc) · 1.68 KB
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
const { Compilation } = require('webpack');
class RemoveCodeBetweenCommentsPlugin {
constructor(options) {
this.options = options;
}
apply(compiler) {
compiler.hooks.compilation.tap('RemoveCodeBetweenCommentsPlugin', (compilation) => {
compilation.hooks.processAssets.tap(
{
name: 'RemoveCodeBetweenCommentsPlugin',
stage: Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE,
},
(assets) => {
for (const assetName in assets) {
if (Object.prototype.hasOwnProperty.call(assets, assetName)) {
if (assetName.endsWith('.js') || assetName.endsWith('.tsx')) { // Only process .js or .tsx files
const asset = assets[assetName];
const source = asset.source();
const updatedSource = this.removeCodeBetweenComments(source);
compilation.updateAsset(assetName, new compilation.compiler.webpack.sources.RawSource(updatedSource));
}
}
}
}
);
});
}
removeCodeBetweenComments(source) {
const { startComment, endComment } = this.options;
const startRegex = new RegExp(`//\\s*${startComment}`, 'g');
const endRegex = new RegExp(`//\\s*${endComment}`, 'g');
let inRemoveBlock = false;
const lines = source.split('\n');
const updatedLines = lines.filter((line) => {
if (startRegex.test(line)) {
inRemoveBlock = true;
return false;
}
if (endRegex.test(line)) {
inRemoveBlock = false;
return false;
}
return !inRemoveBlock;
});
return updatedLines.join('\n');
}
}
module.exports = RemoveCodeBetweenCommentsPlugin;