Tips for stopping TypeScript code blocks from being compiled by the Angular AOT Webpack plugin

Is there a way to exclude specific code from Angular's AOT compiler? For instance, the webpack-strip-block loader can be utilized to eliminate code between comments during production.

export class SomeComponent implements OnInit {
  ngOnInit() {
    /* develblock:start */
    alert("Show in development only"); // Oops. This still appears in production.
    /* develblock:end */
  }
}

Specifically, I am looking for ways to exclude an entire NgModule (e.g. TestModule) from compilation. One possible approach could involve removing the line(s) in the app-routing.module that define the route. For example:

// app-routing.module
const routes: Routes = [
 {
    /* develblock:start */
    path: 'test', loadChildren: './test/test.module#TestModule'
    /* develblock:end */
 }
]

// webpack.config.js 
{
    test: /(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/,
    use: [
      { loader: '@ngtools/webpack' },
      { loader: 'webpack-strip-block' }
    ]
}

Please note that this is not a question exclusively about the webpack-strip-block plugin. It is being used here as an illustration to convey my intention. The plugin's creator has indicated that it may not work with the AngularCompilerPlugin. While the plugin does function with CSS files, that is not the main focus.

Various attempts have been made to achieve this:

1. Using Webpack exclude (or include). Excluding the folder leads to compiler errors as the application code relies on TestModule.

{
  test: /(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/,
  loader: '@ngtools/webpack',
  exclude: path.resolve(__dirname, 'src/app/test')
},

2. Using NODE_ENV for conditional loading of routes. Integrating if statements within an array of objects results in compiler errors.

const routes: Routes = [{
  if (process.env.NODE_ENV !== 'production') {
    path: 'test', loadChildren: './test/test.module#TestModule'
  }
}];

3. Exploring Webpack Externals. Although attempted, it does not seem suitable for this scenario.

Dependencies:

Angular 6.1.7
TypeScript 2.9.2
Webpack 4.19.1

Answer №1

One way to conditionally include a route in app-routing.module using NODE_ENV in Webpack 4 is by checking the environment:

if (process.env.NODE_ENV === 'development') {
  routes.push({ path: 'sample', loadChildren: './sample/sample.module#SampleModule' });
}

This approach ensures that SampleModule is not compiled during production. Credit goes to Pavel Agarkov for suggesting adding the route object to the array.

Answer №2

If you want to set a global variable replacement for var NODE_ENV, you can utilize the DefinePlugin in your webpack configuration:

// Configure webpack
plugins: [
    new webpack.DefinePlugin({
        NODE_ENV: JSON.stringify(process.env.NODE_ENV)
    })
]

You can then reference this variable like so:

declare const NODE_ENV: string;

if (NODE_ENV !== 'production') {
    routes.push({ path: 'test', loadChildren: './test/test.module#TestModule' });
}

Webpack will replace NODE_ENV with its value. During production, it will be 'production'. This means that any code inside

if ('production' !== 'production')
will be removed by AOT as it is unreachable.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using the decorator in VueJS Typescript allows you to easily define dynamic computed properties

On my hands is a component structured like this: @Component({ computed: { [this.stateModel]: { get() { return this.$store[this.stateModel]; } } } }) class Component extends Vue{ @Prop({ de ...

Error: The code encounters a SyntaxError due to an unexpected token '?' in iOS 14

Currently in the process of developing a Headless Shopify project using this starter: https://github.com/vercel/commerce. While testing the demo environment, I encountered some bugs that seem to be specific to iOS 14 or newer. The primary issue stems from ...

Tips for accurately mapping JSON from an Angular 5 POST request to a Java entity with RestEasy integration

Below is code snippet from an Angular 5 component: export class TripsComponent implements OnInit { ... ... addTrip() { let newTrip = new Trip(this.new_trip_name, this.new_trip_description, this.company); this.tripService.addTrip(newTrip).t ...

Create a solution that is compatible with both web browsers and Node.js

I am developing a versatile library that can be utilized in both the browser and in node environment. The project involves three json config files, with the latter two extending the tsconfig.json. tsconfig.json (contains build files) tsconfig.browser.js ...

Backend external login without password feature in .NET Core ABP 6.0 for users

Currently, I am working on a project that involves utilizing ABP 6.0 native backend (.NET Core 6 with IdentityServer) and a non-native angular frontend project with ABP installed for the static proxy tool. I am encountering difficulties in implementing Goo ...

Encountering a Typescript TypeError in es2022 that is not present in es2021

I'm attempting to switch the target property in the tsconfig.json file from es2015 to es2022, but I am encountering an error while running tests that seem to only use tsc without babel: Chrome Headless 110.0.5481.177 (Mac OS 10.15.7) TypeError: Can ...

Errors may arise in Typescript when attempting to block the default behavior of DataGrid onRowEditStop

Hey there! I'm new to posting questions here and could use some help. I'm encountering a minor issue while trying to prevent the default behavior of the "Enter" key in the "onRowEditStop" method of the DataGrid component. Here's my code sni ...

Error: THREE.MTLLoader cannot be instantiated 2.0

Previously, I posted a question regarding this issue: Uncaught TypeError: THREE.MTLLoader is not a constructor I was able to resolve it by modifying the three-mtl-loader file. However, since I plan to upload my work to GitHub later, I need to find a solut ...

Unusual problem arises with scoping when employing typeguards

Consider the following TypeScript code snippet: interface A { bar: string; } const isA = <T>(obj: T): obj is T & A => { obj['bar'] = 'world'; return true; } let obj = { foo: 'hello' }; if (!isA(obj)) thro ...

Difficulty encountered when trying to apply a decorator within a permission guard

I'm a newcomer to Nestjs and I am currently working on implementing Authorization using Casl. To achieve this, I have created a custom decorator as shown below: import { SetMetadata } from '@nestjs/common'; export const Permission = (acti ...

"Utilizing jQuery and Bootstrap 4 in TypeScript, attempting to close modal window using jQuery is not functioning

Trying to make use of jquery to close a bootstrap modal within an angular project using typescript code. The following is the code: function call in html: (click)="populaterfpfromsaved(i, createSaved, createProp)" createSaved and createProp are local ...

What is the process for upgrading ag-Grid to newer versions?

In the past, I was using: "ag-grid": "^18.1.2", "ag-grid-angular": "^18.1.1" Version "^18.1.1" of "ag-grid-enterprise". However, as my license expired, I obtained new versions of the licenses. I then included: "@ag-grid-community/angular": "^22.1.1", ...

Leveraging webpack for CSS bundling

I'm currently working on bundling some NPM modules using webpack instead of utilizing a CDN. While I've successfully managed to integrate the .js files, I'm facing challenges with including the .css files for these modules. One example is ...

Using TypeScript in the current class, transform a class member into a string

When converting a class member name to a string, I rely on the following function. However, in the example provided, we consistently need to specify the name of the Current Component. Is there a way to adjust the export function so that it always refers ...

How to navigate to an anchor tag on a separate page using Angular 9

Is there a way in Angular 9 to create a link that directs to a specific section on a page like I would in plain HTML using <a href="myPage#mySection">go to my section</a>? I've come across outdated solutions when searching for this, so I&a ...

What is the method to retrieve the total number of days in a moment-jalaali using NodeJS?

I'm trying to determine the number of days in the moment-jalaali package for NodeJS. Despite checking their API on GitHub, I couldn't find any reference to a specific method like numOfDay. ...

Display a second dialog to the left of the first dialog at the same level using Angular Material

Scenario: I have a customer record and would like to show additional read-only information in a separate dialog. This requires some selections. In Angular Material, I already have one modal dialog open and find it relatively easy to open a second one. Che ...

What is the reason for webpack searching for jQuery even though it is not necessary for the module?

Before I proceed with my question, I want to clarify that I may not fully grasp the intricacies of this issue and I apologize if it does not meet the standards of Stackoverflow's Q&A. Currently, we are facing a challenge in our project while tryi ...

Angular does not permit the use of the property proxyConfig

Click here to view the image I encountered an issue when attempting to include a proxy config file in angular.json, as it was stating that the property is not allowed. ...

API endpoint generating a Vue component as a rendered output

In the process of developing a document templater service, I am faced with the challenge of handling numerous document templates (contracts, protocols, etc.) written in Vue. The concept revolves around clients sending props in the body, which are then pass ...