Angular 根据环境变量的值引发编译时错误
如何在angular中引发编译器时间错误,使编译器不会继续并根据Environments.ts文件中的值给出错误。例如,考虑下面的场景,其中应用程序应该使用认证方法1或2,但不能同时使用: environment.ts包含以下内容:Angular 根据环境变量的值引发编译时错误,angular,typescript,angular-cli,angular9,angular-aot,Angular,Typescript,Angular Cli,Angular9,Angular Aot,如何在angular中引发编译器时间错误,使编译器不会继续并根据Environments.ts文件中的值给出错误。例如,考虑下面的场景,其中应用程序应该使用认证方法1或2,但不能同时使用: environment.ts包含以下内容: export const environment = { production: false, enableAuthenticationMethod1: true, enableAuthenticationMethod2: false }; expor
export const environment = {
production: false,
enableAuthenticationMethod1: true,
enableAuthenticationMethod2: false
};
export const environment = {
production: true,
enableAuthenticationMethod1: false,
enableAuthenticationMethod2: true
};
而environment.prod.ts包含以下内容:
export const environment = {
production: false,
enableAuthenticationMethod1: true,
enableAuthenticationMethod2: false
};
export const environment = {
production: true,
enableAuthenticationMethod1: false,
enableAuthenticationMethod2: true
};
现在在prod模式下,我们禁用了AuthenticationMethod1,启用了AuthenticationMethod2。如何确保将引发包含以下(错误)内容的环境文件的编译时错误:
export const environment = {
production: true,
enableAuthenticationMethod1: true,
enableAuthenticationMethod2: true
};
没有任何OOTB方法在编译期间引发异常。我认为唯一可行的方法是弹出webpack配置并创建一个插件来验证您的设置。(我不建议弹出webpack配置,除非您必须这样做) 但是,您可以创建一个自定义的TSLint规则来检查您的
environment.ts
,查看设置是否有效
禁止所有导入语句的TSLint规则示例:
import * as Lint from "tslint";
import * as ts from "typescript";
export class Rule extends Lint.Rules.AbstractRule {
public static FAILURE_STRING = "import statement forbidden";
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithWalker(new NoImportsWalker(sourceFile, this.getOptions()));
}
}
// The walker takes care of all the work.
class NoImportsWalker extends Lint.RuleWalker {
public visitImportDeclaration(node: ts.ImportDeclaration) {
// create a failure at the current position
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING));
// call the base version of this visitor to actually parse this node
super.visitImportDeclaration(node);
}
}
我认为这是一个设计问题。在您的environment.ts中我只需要一个属性,它是一个authenticationMethod
,它是auth方法的字符串。这样,您可以拥有任意数量的组合,而不必为n个组合执行逻辑,这是演示问题的示例场景。很明显,我知道如何使用字符串检查某些代码条件。我想知道如何从代码中引发编译时错误。