Home > database >  Can I exclude features (routes, components...) in my Angular application during Build time depending
Can I exclude features (routes, components...) in my Angular application during Build time depending

Time:06-14

I would like to have two versions of my Application with the same codebase. One Version should for example include the "registration" feature and the other one not. Can I configure Angular somehow that an env file determines what gets excluded during compilation? Or does the compiler anyway remove unreachable code. For example, if I have two feature.json files and each build process gets one of them. And in my code I just check if the feature is activated in my feature.json

CodePudding user response:

Yes, angular has this built in. There are already two different compilation versions by default: production and development. You can add more. The environment objects are found in the environments directory. The build configurations are in angular.json. When building you use the command ng build --configuration=myConfigurationName.

Here's the docs: https://angular.io/guide/build

Here's the default configurations:

          "configurations": {
            "production": {
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "500kb",
                  "maximumError": "1mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "2kb",
                  "maximumError": "4kb"
                }
              ],
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "outputHashing": "all"
            },
            "development": {
              "buildOptimizer": false,
              "optimization": false,
              "vendorChunk": true,
              "extractLicenses": false,
              "sourceMap": true,
              "namedChunks": true
            }
          },
          "defaultConfiguration": "production"

Notice how in production, the environment.ts file gets replaced by the environment.prod.ts file.

So you have two options:

  1. You can create two new environment files and use boolean feature toggles to include and exclude functionality. So you import the object from environment.ts, but you replace that environment file during compilation. The issue is anyone can still activate that functionality using the debugger.

  2. You can have two versions of specific files and replace those files depending on what version you want. The downside is it'll be extra work to keep common functionality synced between versions. Anything that is not common will need to be in separate files.

  • Related