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

Is it possible to define data types for the global context in cucumber?

Embarking on a fresh cucumber-selenium project in Typescript, I am eager to keep the Driver in the world context. However, following the method suggested here, I encounter an issue where the Driver type remains inaccessible to step definitions. This means ...

Having trouble setting the default value of a select element with 'selected' in Angular's bootstrap?

Click here I've been facing some difficulties in making the 'selected' tag work to pre-select my default select value. It seems like it might be related to the unique pipe I'm using and how Angular handles it. I have experimented with ...

Updating the style of different input elements using Angular's dynamic CSS properties

I am seeking guidance on the proper method for achieving a specific functionality. I have a set of buttons, and I would like the opacity of a button to increase when it is pressed. Here is the approach I have taken so far, but I have doubts about its eff ...

Customize the initial color of the text field in Material UI

I am currently working with the mui TextField component and facing an issue. I am able to change the color when it is focused using the theme, but I cannot find a way to adjust its color (label and border) in its initial state when it's not focused. I ...

Generating dynamic text in Angular based on certain conditions

I am still learning about Angular. Can someone please explain how to make text dynamic based on a count? For example, if the count is greater than 2, the text should be "Teams," and if it is less than or equal to 2, the text should be "Team." Here is what ...

Adding a project to TFS source control using Visual Studio Code: a step-by-step guide

Looking for guidance on adding an Angular 4 project developed with Visual Studio Code (version 1.18.0) to TFS source control. I've already installed the TFS extension (version 0.6.0) in Visual Studio Code, but unsure how to map the project folder to T ...

How can a mock document be utilized in a unit test for an imported TypeScript dependency?

To effectively unit-test a legacy TypeScript class, I am seeking ways to mock the document object. The class has dependencies on another class (View.ts), which in turn relies on a 3rd party module that further depends on the existence of the document. The ...

Instructions for transferring an Angular / Node.js application to a different computer

Hey there! I'm in the process of transferring my project to a new computer. Just to let you know, I've already set up node.js and mongoDB on the new machine. When it comes to the Angular app, I understand that I need to copy over the frontEnd d ...

Angular7 & Electron: Resolving the Issue of Loading Local Resources

I am encountering difficulties while working with electron. Although I can successfully load my project using ng serve, I encounter an error when attempting to open it with electron as shown in the developer tools Not allowed to load local resource: fil ...

What made the "in" operator not the best choice in this situation?

When I set out to create a type that represents the values of a given object type, I initially came up with this: type Book = { name:string, year:number, author:string } // expected result "string" | "number" type ValueOf<T ex ...

A tutorial on ensuring Angular loads data prior to attempting to load a module

Just starting my Angular journey... Here's some code snippet: ngOnInit(): void { this.getProduct(); } getProduct(): void { const id = +this.route.snapshot.paramMap.get('id'); this.product = this.products.getProduct(id); ...

Transferring information to a deep-level interface

I am currently working on creating an object that aligns with my interface structure. Success Story export interface ServiceDataToDialog { id: number, service: string, } constructor(private _dialogRef: MatDialogRef<DialogServiceTabletAddRowComp ...

Using getters in a template can activate the Angular change detection cycle

When using getters inside templates, it seems that Angular's change detection can get stuck in a loop with the getter being called multiple times. Despite researching similar issues, I have not been able to find a clear solution. Background info: I ...

Encountering an issue with resolving parameters for the DecimalPipe in ngBootstrap/Angular2

Just delving into the world of Angular2 and trying to learn through hands-on experience. However, I've hit a roadblock! I attempted to import ng-bootstrap and encountered this error: https://i.stack.imgur.com/QDVJ3.png Here's my systemjs.config ...

Problems arising from the layout of the PrimeNG DataView component when used alongside Prime

I've been working with a PrimeNG DataView component that requires the use of PrimeFlex's flex grid CSS classes to set up the grid structure. One of their examples includes the following instructions: When in grid mode, the ng-template element ...

How is it possible for the igx-expansion-panel to close when there is a nested angular accordion present?

Currently, I am faced with the challenge of closing the igx-expansion-panel within my Angular project. While everything functions smoothly with a standard panel, things get a bit tricky when dealing with nested angular accordion structures using igx-accord ...

Having trouble getting the Next.js Custom Server to function properly with Firebase

I have deployed my Next.js App on Firebase and I am using a custom server (server.ts) to launch the app (node src/server.ts). The code for the server.ts file along with firebaseFunctions.js is provided below. The server.ts file works fine locally, which ...

NextJS React - WebpackError: Cannot access 'window' before initialization

I'm delving into the world of React and recently completed the "Getting Started" tutorial for NextJs (link), successfully setting up a new project. However, when attempting to import third-party plugins like current-devices or smooth-scrollbar, I enc ...

Struggling to integrate authentication and authorization features into a ReactJS application with Microsoft Azure AD or Database login functionality

We have an application built on React v18 with a backend that includes a Web API and SQL Server database. Our requirement is to authenticate and authorize users using either MS Azure AD or the database. If a user attempts to log in with a username and pas ...

Displaying data in a table using NgFor and allowing the user to input the number of columns

My component has the capability to accept an array input, such as [1, 2, 3, 4, 5, 6, 7], and a number of columns input. For example, if a user specifies 3 columns, I want to display the data in a table with 3 columns like this: 1 2 3 4 5 6 7 If the ...