0

How can I raise a compiler time error in angular so the compiler will not proceed and give me error depending on the values inside my enviroments.ts file. For instance consider the following scenario in which the application should use either authentication method 1 or 2 but not both :

environment.ts has the following content:

export const environment = {
  production: false,
  enableAuthenticationMethod1: true,
  enableAuthenticationMethod2: false
};

while environment.prod.ts has the following content:

export const environment = {
  production: true,
  enableAuthenticationMethod1: false,
  enableAuthenticationMethod2: true
};

Now in prod mode we have AuthenticationMethod1 disabled and AuthenticationMethod2 enabled. How can I make sure a compile time error for an environment file with the following (wrong) content will be raised:

export const environment = {
  production: true,
  enableAuthenticationMethod1: true,
  enableAuthenticationMethod2: true
};
MHOOS
  • 5,146
  • 11
  • 39
  • 74
  • I think this is a design problem. I would just have a single property in your environment.ts that is a `authenticationMethod` which would be a string of the auth method. That way, you can have as many as you want opposed to having to do logic for n number of combinations – mwilson Mar 09 '20 at 22:06
  • That was a sample scenario to demonstrate the problem. I know obviously how to use a string for checking some code condition. I want to know how to raise a compile time error from the code. – MHOOS Mar 09 '20 at 22:10

1 Answers1

0

There isn't any OOTB way to raise an exception during compilation. The only way I see that being possible is if you ejected the webpack config and create a plugin that validates your setup for you. (I wouldn't recommend ejecting webpack config unless you absoloutely have to).

However, what you could do is create a custom TSLint Rule that checks you environment.ts to see if the setup is valid

https://palantir.github.io/tslint/develop/custom-rules/

Example TSLint rule that prevents all import statements:

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);
    }
}
mwilson
  • 12,295
  • 7
  • 55
  • 95