regex 正则表达式使Angular编译速度变慢

rta7y2nd  于 2023-05-30  发布在  Angular
关注(0)|答案(1)|浏览(122)

Angular不会编译包含142个正则表达式的服务。前50个还可以,但是每增加一个正则表达式就会减慢编译速度。它停在77(Generating browser application bundles...)。
该服务将西班牙语单词转录为国际音标(IPA)。下面是代码的一个示例。

// Rule 12, 'v'
  // if the word includes 'v'
  if (word.includes('v')) {
    rulesArray.push('12');

    // if 'v' is the first letter
    if (word.charAt(0) === 'v') {
      ipaWord = ipaWord.replace('v', '7'); // replace 'v' with '7'
    }

    // if word includes 'mv'
    if (word.includes('mv')) {
      regexp = /mv/gi
      ipaWord = ipaWord.replace(regexp, 'm7'); // replace 'mv' with 'm7'
    }

    // if word includes 'nv'
    if (word.includes('nv')) {
      regexp = /nv/gi
      ipaWord = ipaWord.replace(regexp, 'n7');  // replace 'nv' with 'n7'
    }

    regexp = /v/gi
    ipaWord = ipaWord.replace(regexp, 'β'); // replace 'v' with 'β' in all other cases

    regexp = /7/gi
    ipaWord = ipaWord.replace(regexp, 'b');  // restore 'b'
  } // close Rule 12, if the word includes 'v'

我几年前为Firebase的Cloud Functions写了这段代码,它在那里工作得很好。我只是想我可以保存一个网络调用,让我的应用程序运行得更快,通过在Angular(同步)中使用这个服务,而不是调用云函数(异步)。
是我做错了什么,还是Angular讨厌正则表达式?
活动监视器显示CPU空闲率为65%,内存压力低,能耗、磁盘和网络活动低。我听到风扇转得很厉害,我能感觉到电脑很热。有没有一种方法可以使用Chrome开发者工具来查看哪些代码被停止?
Visual Studio代码对同一文件有问题。原始文件是JavaScript,我将其转换为TypeScript,这需要在顶部声明变量。当变量在顶部声明时,VSCode会抛出错误,说明变量没有被声明。退出并重新启动TypeScript可以修复错误。
如果我是个天才,我可能会把142个正则表达式重写成一个超级正则表达式,但这对其他人来说是不可读的。

kg7wmglp

kg7wmglp1#

我通过将文件分成16个文件来解决这个问题。

word = spanishPhonologyRule1(word) as string;
    word = spanishPhonologyRule13(word) as string;
    word = spanishPhonologyRule12(word) as string;
    word = spanishPhonologyRule2(word, shortAccent) as string;
    word = spanishPhonologyRule3(word) as string;
    word = spanishPhonologyRule4(word) as string;
    word = spanishPhonologyRule11(word) as string;
    word = spanishPhonologyRule5(word) as string;
    word = spanishPhonologyRule6(word) as string;
    word = spanishPhonologyRule7(word) as string;
    word = spanishPhonologyRule8(word) as string;
    word = spanishPhonologyRule9(word) as string;
    word = spanishPhonologyRule10(word) as string;
    word = spanishPhonologyRule14(word, shortAccent) as string;
    word = spanishPhonologyRule15(word, shortAccent) as string;

我尝试将文件移动到Firebase的Cloud Functions,但编译器也变慢并停止。在Cloud Functions中编译的原始JavaScript文件没有问题。问题似乎是TypeScript不能编译超过60或70个正则表达式,而JavaScript编译100+正则表达式时没有减速。

相关问题