SyntaxError: Invalid regular expression

SyntaxError: Invalid regular expression

我将 webpack 版本从 4.0.0 更新到 5.52.1 并在使用 'bin/webpack' 编译后得到了结果webpack 5.52.1是否编译成功
但是,我收到如下错误消息

SyntaxError: Invalid regular expression: /^(https?://)?((([a-zd]([a-zd-]*[a-zd])*).)+[a-z]{2,}|((d{1,3}.){3}d{1,3}))(:d+)?(/[-a-zd%_.~+]*)*(?[&a-zd%_.~+=-]*)?(#[-a-zd_]*)?$/: Invalid group
    at new RegExp (<anonymous>)
    at /node_modules/webpack/lib/javascript/JavascriptParser.js:410:24
    at Hook.eval [as call] (eval at create (/node_modules/tapable/lib/HookCodeFactory.js:19:10), <anonymous>:7:16)
    at JavascriptParser.evaluateExpression (/node_modules/webpack/lib/javascript/JavascriptParser.js:3150:25)
    at JavascriptParser.getRenameIdentifier (/node_modules/webpack/lib/javascript/JavascriptParser.js:1366:23)
    at JavascriptParser.walkVariableDeclaration (/node_modules/webpack/lib/javascript/JavascriptParser.js:2058:31)
    at JavascriptParser.walkStatement (/node_modules/webpack/lib/javascript/JavascriptParser.js:1566:10)
    at JavascriptParser.walkStatements (/node_modules/webpack/lib/javascript/JavascriptParser.js:1427:9)
    at /node_modules/webpack/lib/javascript/JavascriptParser.js:1601:9
    at JavascriptParser.inBlockScope (/node_modules/webpack/lib/javascript/JavascriptParser.js:3048:3)
.
.
.
webpack 5.52.1 compiled successfully

我对此一无所知,因为我可以使用 webpack 4.0.0 进行编译而不会出现错误消息,但是在迁移到 webpack 5.52.1 之后,我在 new RegExp /node_modules/webpack/lib/javascript/JavascriptParser.js 并且没有 /^(https?://)?(((a-zd).)+ [a-z]{2,}|((d{1,3}.){3}d{1,3}))(:d+)?(/[-a-zd%_.~+])(?[&a-zd%_.~+=-])?(#[-a-zd_]*)?$/ 在我的脚本中谁能告诉我如何找到根本原因并解决这个问题

资源:
rails: 6.1.4
webpacker: 6.0.0.rc.2
webpack: 5.52.1
webpack-cli: 4.8.0

您需要假装反斜杠来转义正则表达式中的斜杠。此外,您在倒数第二组的开头有一个多余的 ?

^(https?:\/\/)?((([a-zd]([a-zd-]*[a-zd])*).)+[a-z]{2,}|((d{1,3}.){3}d{1,3}))(:d+)?(\/[-a-zd%_.~+]*)*([&a-zd%_.~+=-]*)?(#[-a-zd_]*)?$

您在 (? 后忘记了一个冒号并且丢失了反斜杠,在构造函数中将它们加倍:

new RegExp('^(https?://)?((([a-z\d]([a-z\d-]*[a-z\d])*)\.)+[a-z]{2,}|((\d{1,3}\.){3}\d{1,3}))(:\d+)?(/[-a-z\d%_.~+]*)*(?:[&a-z\d%_.~+=-]*)?(#[-a-z\d_]*)?$')

否则使用正则表达式文字:

/^(https?:\/\/)?((([a-z\d]([a-z\d-]*[a-z\d])*)\.)+[a-z]{2,}|((\d{1,3}\.){3}\d{1,3}))(:\d+)?(\/[-a-z\d%_.~+]*)*(?:[&a-z\d%_.~+=-]*)?(#[-a-z\d_]*)?$/

我可以通过以下步骤修复它

  1. webpacker 更改为 shakapacker
  2. 更新 const componentRequireContext = 的语法 require.context("组件", 真);常量 componentRequireContext = require.context( "组件", true, /^(https?://)?(((a-z\d).)+[a-z]{2,}|((\d{1,3}.) {3}\d{1,3}))(:\d+)?(/[-a-z\d%_.~+])(?:[&a-z\d%_.~+=-])?(#[-a-z\d_]*)?$/ );