ng build因为正则表达式出现错误。

3

我在常量中有一个正则表达式:

export const Constants = {
    QUERY_PARAM_CONFIG: {
        REGEX: /\+/gi,
        REGEX_ENCODED: /%2B/g
    }
};

但是当我运行ng build时,出现了错误:
ERROR in app\app.module.ts(58,21): Error during template compile of 'AppModule'
  Expression form not supported in 'Constants'
    'Constants' contains the error at app\configuration\constants.ts.

npm构建脚本:

ng build --prod --output-hashing none --sourcemaps=true

有什么想法吗?


可能问题出在你使用它的方式上,而不是定义它的方式上。请在你的AppModule中发布一段代码。同时,请发布你正在执行的确切命令(例如 ng build vs. ng build --prod)。 - Pavel Agarkov
1个回答

10

正则表达式文本不支持AOT。请参阅支持语法列表

为了使其工作,请将您的正则表达式转换为支持的内容,例如字符串:

const before = /\+/gi, // before, could be the same as below

const after = { re: '\\+', flags: 'gi' }
const canBeUsedAs = new RegExp(after.re, after.flags);

通过这种方式,您仍然可以传递RegExp的含义,并在运行时需要时动态创建一个。


1
我使用text-mask库时遇到了同样的问题。我需要提供一个正则表达式数组,例如[ / \ d /,/ \ d /,'。',/ \ d / ],但是如果我使用 [ new RegExp('\d/'), new RegExp('\d/'), '.', new RegExp('\d/') ] 它不起作用... :( - JoG
我有同样的问题 /translate3d(\s?(?<x>[-]?\d*)px,\s?(?<y>[-]?\d*)px,\s?(?<z>[-]?\d*)px)/ 你能帮我解决吗? - Bhargav Patel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接