Comparison Between Angular 4 `ng serve --prod` and `ng serve` Commands

So, here's the situation: I have an app that is 4.6MB when running on ng serve.

When I run:

ng serve --prod

The file size drops to 1MB.

However, when I use --prod, my entire application breaks.

All of my services (which are promise-based) that send requests to the server stop working.

The strange thing is that just using ng serve works fine and certain parts of ng serve --prod work as well, as long as there are no server requests involved.

I'm not including any code since the version with ng serve functions correctly.

The question remains:

Why am I experiencing this behavior?

Furthermore, at times, the app using ng serve --prod suddenly starts working perfectly out of nowhere, only to break again after restarting the app.

EDIT: more DETAILS:

I've used Fiddler to verify all the details:

https://i.sstatic.net/Zsqe8.png

As you can see, everything checks out.

Now, here's the code responsible for simulating the request on the client side:

    login(uName: string, pw: string, type: number): Promise<any> {
    return new Promise(resolve => {
        if (type === 1) {
            const options = new RequestOptions({ headers: this.headers });
            const body = JSON.stringify({ username: uName, password: pw });
            this.http.post(this.loginUrl, body, options)
                .toPromise()
                .then(response => {
                    resolve(response);
                })
                .catch(this.handleError);
        } else if (type === 2 || type === 3) {
            this.http.post(this.loginUrl, { username: uName, token: pw })
                .toPromise()
                .then(response => {
                    resolve(response);
                })
                .catch(this.handleError);
        }
    });
}

Everything works flawlessly when I use ng serve alone (Network Tab):

https://i.sstatic.net/SMvaP.png

As shown, I'm logged in and receiving a response.

However,

As soon as I run

ng serve --prod

The same login request with the same details stops functioning:

https://i.sstatic.net/3z9Cc.jpg

This is extremely puzzling.

All of my methods handling server requests remain unchanged.

I receive a "Bad Request" error with some error code from the server itself (like "email not filled", which is also odd considering I am sending the correct parameters)

Answer №1

Running ng serve --prod in Angular CLI creates a production build with tree shaking and AOT (Ahead Of Time) compilation, resulting in less code compared to a normal build. This command allows you to preview how your application will perform in production mode.

Tree shaking eliminates unused components from the codebase, only including those that are actually used. This is why the vendor.js file is significantly smaller when using ng serve --prod.

A downside of this approach is that the compiled and minified code is less debuggable.

For more information on each build process, refer to the CLI documentation.

Answer №2

--prod is the build option that enables debug mode by default.

Consider an example to understand why an application may break. Suppose we have the following code:

<div (click)="toshow = !toShow">Toggle</div>

Now, imagine that toshow is not defined in the component or there is a typo where toShow is mistakenly written as toshow.

In such a scenario, running ng build and ng serve will work fine. However, using ng build --prod and ng serve --prod will result in an error.

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

Tips for Maintaining User Data Across Pages in React using React-Router-Dom and Context

I've been tackling the login functionality of a client-side application. Utilizing React alongside TypeScript, I've incorporated react-router-dom and Context to manage the user's data when they log in. However, upon refreshing the page, the ...

How can I use jQuery to switch the positions of two <div> elements in HTML based on the selection of a dropdown value?

I need to switch the display positions of two <div> containers based on a dropdown value change. Can this be accomplished using jQuery? Here are the two div containers whose display positions need to be interchanged: <div id="first"><p> ...

Is there a way to verify the selection of all mandatory fields prior to concealing a div?

var count = 2; $('.next').click(function() { var requiredField = true; $(this).siblings('table').find('tbody tr:nth-child(' + count + ') td').each(function() { var element = $(this).find('center').f ...

The resize function triggers twice as many events with each window resize

While working on my website, I encountered a navigation issue when resizing the browser from desktop to mobile size. Initially, the mobile menu worked on load, as did the desktop navigation. However, after running a script with $(window).on('resize&ap ...

Executing asynchronous actions with useEffect

Within my useEffect hook, I am making several API requests: useEffect(() => { dispatch(action1()); dispatch(action2()); dispatch(action3()); }, []); I want to implement a 'loading' parameter using async/await functions in the hook ...

Warning message regarding unhandled promise rejection in NestJS websockets

I've encountered a puzzling issue while attempting to integrate an 'events' module into my application to utilize websockets. Upon adding the module, an unexpected error surfaced: (node:59905) UnhandledPromiseRejectionWarning: Unhandled pro ...

Reducing the size of textures in three.js

Is it possible to shrink the faces of a model rendered in the browser using Threejs, without affecting the mesh structure? I am looking for suggestions on how to accomplish this unique task. ...

JavaScript: "Changing the date string to a different format"

Looking to convert a date string from yyyy-MM-dd HH:mm:ss.SSS in PST timezone to UTC format 2016-07-28T17:22:51.916Z. Any ideas on how to achieve this transformation? ...

Server-side WebSocket doesn't appear to be successfully transmitting messages to the frontend

Using NodeJs with Fastify on the backend in a local environment: Server side: ////// Setting up the app const fastify = require('fastify')({ logger: true }); const path = require('path'); fastify.register(require('@fastify/static& ...

Press the "submit" button to perform an onclick event just before the form's "action" is executed

Here is a form that allows you to select a CSV file and upload it to a MySQL server: <form class="ui input" enctype="multipart/form-data" method = "POST" action="trend_upload_csv.php" role = "form"> <input type = "file" name ="file" id="file" ...

Step-by-step guide on incorporating Google Fonts and Material Icons into Vue 3 custom web components

While developing custom web components with Vue 3 for use in various web applications, I encountered an issue related to importing fonts and Google material icons due to the shadow-root. Currently, my workaround involves adding the stylesheet link tag to t ...

What is the process for implementing JavaScript in Django?

I'm a newcomer to this and although I've tried searching on Google, I haven't found a solution. I'm facing an issue where I can include JavaScript within the HTML file, but it doesn't work when I try to separate it into its own fil ...

What is the best way to create a sliding <nav> effect when a <div> is clicked?

Hello! I am looking for a solution that will cause the navigation contents to slide out from the left when the div class "bt-menu" is clicked. It should also slide back in to the left either when the div is clicked again or when anywhere outside of the nav ...

Using AngularJS to bind objects with a checkbox

I am dealing with a nested list of objects that can go up to three levels deep. Each object contains another nested object, and this nesting can continue to multiple levels. I am interested in binding these objects directly to checkboxes so that when I che ...

Prevent automatic scrolling by clicking when you reach the bottom

In order to replicate the issue I am experiencing, please click on the down button four times, and then click on the up button. You will observe that you need to click the up button one extra time for it to function properly. How can I detect when it has r ...

Is there a way to make a link clickable but also prevent another link from being activated when clicked?

Have you ever utilized #link to navigate to a specific section on a webpage? You can also incorporate animate and scrollTop() to ensure a smooth scroll. However, when the #link (Hash link) is situated in the navigation menu, it must be structured as exampl ...

What steps can be taken to resolve the error ERROR TypeError: undefined is not an object when evaluating 'userData.username'?

.I need help fixing this error ERROR TypeError: undefined is not an object (evaluating 'userData.username') Currently, I am working on a small application where users are required to allow permission for their location in order to save their cit ...

What is the proper way to utilize BrowserRouter when child routes are connected to components?

I recently started learning React and decided to create a signup form following a tutorial on React Tutorial. However, the tutorial turned out to be outdated. I attempted to implement browser redirects for the signup, login, and home page links by defining ...

Upgrade the WordPress light editor to the advanced version

After developing a script to upgrade the WordPress editor on a specific page from light mode to Advanced once a user clicks the Unlock button and confirms their desire to make the switch, an issue arose. Despite deducting 5 coins from the user's balan ...

Determine the DOM element that corresponds to a right-click action

I utilized the code snippet below to construct a personalized context menu: <script type="text/javascript"> $(document).ready(function() { var x, y; document.oncontextmenu = function(e) { e.preventDefault(); x = e.clientX; ...