Migration Script to Replace Lines in All Files

JS
S
JavaScript

This resource provides a powerful migration script to efficiently replace specific lines across multiple files in a codebase. Ideal for large-scale refactoring or updating deprecated code, it streamlines the process of making consistent changes across an entire project, saving developers time and reducing errors.

1const hasUntilDestroy = /import\s*{\s*[^}]*untilDestroyed[^}]*}\s*from\s*("|')ngx-take-until-destroy\1(?=[^]*untilDestroyed\(\w*\)[^]*)/;
2const catchImport = /import\s*{\s*[^}]*untilDestroyed[^}]*}\s*from\s*("|')ngx-take-until-destroy['|"];/;
3
4const glob = require('glob');
5const fs = require('fs');
6
7const base = `src/app`;
8
9glob(`${base}/**/*.ts`, {}, function(er, files) {
10  files.forEach(path => {
11    fs.readFile(path, 'utf8', function(err, text) {
12      if (hasUntilDestroy.test(text)) {
13        console.log(`Replaced ${path}`);
14        const result = text
15          .replace(
16            /((?:@\w*\([^]*\)[\n\s\r\t]*)(?=([\n\s\r\t]*export[\s\r\t]*class))\2)/,
17            '@UntilDestroy()\n$1'
18          )
19          .replace(
20            catchImport,
21            `import { untilDestroyed, UntilDestroy } from '@ngneat/until-destroy';`
22          );
23        fs.writeFile(path, result, 'utf8', function(err) {
24          if (err) return console.log(err);
25        });
26      }
27    });
28  });
29});

Created on 3/4/2020