Is there a method to instruct angular-cli (for angular 2) to produce a minified version of css files?

When running "ng serve" in angular-cli, the generated css is not minified as expected. Is there a specific setting to configure in angular-cli-build or an additional plugin to install?

This is the content of my angular-cli-build.js file:

var Angular2App = require('angular-cli/lib/broccoli/angular2-app');

module.exports = function(defaults) {
  return new Angular2App(defaults, {
    vendorNpmFiles: [
      'systemjs/dist/system-polyfills.js',
      'systemjs/dist/system.src.js',
      'zone.js/dist/**/*.+(js|js.map)',
      'es6-shim/es6-shim.js',
      'reflect-metadata/**/*.+(ts|js|js.map)',
      'rxjs/**/*.+(js|js.map)',
      '@angular/**/*.+(js|js.map)',
      'angular2-cookie/**/*.js'
    ]
  });
};

Answer №1

When building for production, use the following command: ng build --prod --env=prod

Or while serving for production, you can use: ng serve --prod

This will minify and add a file hash automatically for you.

  • The --prod flag instructs it to minify, hash, and gzip the files.
  • The --env=prod flag specifies to utilize your production environment constants file.

Here is an illustration of what it would look like

Answer №2

To optimize your code, you can follow these steps:

# --env=<your_env>
# --no-sourcemap
# minify => ./minify.js
ng build --env=prod --no-sourcemap && node minify

Here is the content of minify.js file:

// npm i --save-dev minifier fs-jetpack

const jetpack = require('fs-jetpack');
const path = require('path');
const minifier = require('minifier');

const files = jetpack.list(path.join(__dirname, 'dist'));

console.log(files);

for (const file of files) {
  if (/.*(\.js|\.css)$/g.test(file)) {
    console.log(`Start ${file}`);
    const filePath = path.join(__dirname, 'dist', file);
    minifier.minify(filePath, {output: filePath});
  }
}

console.log('End');

Answer №3

James has successfully tested his commands and confirmed that they do minify when using ng serve --prod.

Despite this, users might be puzzled by what they see in Chrome:

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

At first glance, it may not appear to be minified!

However, a closer look reveals the presence of js:formatted, indicating that the pretty print feature is turned on.

By accessing the URL directly at

http://localhost:4200/main.5082a3da36a8d45dfa42.js
in a new tab, James verified that the CLI indeed performs full minification.

The option to disable the pretty print feature can be accessed by clicking the {} icon, although it tends to disappear once the code has been pretty printed. In such cases, simply reload the page and quickly click the icon again.

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

Answer №4

For the year 2020, simply including the --prod flag during project building is sufficient:

ng build --prod

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 Javascript to display an element when scrolling within a specific container and each item of an array reaches the top

I'm just starting out with JavaScript and I'm attempting to create a scrollable div that includes items from an array. As the user scrolls and each item reaches the top, I want a hidden element to be displayed. Here's what I have so far: ...

Is there a way for me to trigger an action based on the Observable's return

I'm eager to optimize this by implementing observables: post<T>( url: string, body: any, params?: HttpParams, headers?: HttpHeaders ): Observable<T> { this.isLoading$.next(true); const res = this.http .p ...

I rely on a powerful compiler in Angular that is only compatible with the View Engine, yet unfortunately, the View Engine is now obsolete

I recently came across this interesting update: Project is trying to disable the Ivy compiler. Angular versions 12 and above no longer support the deprecated View Engine compiler for applications. Instead, the Ivy compiler will be used for building this pr ...

Ways to transmit additional arguments to RxJS map function

When working with an Angular application, I utilize HttpClient along with RxJS operators to execute various API calls. One example of this is shown below: return this.httpClient.put(url, JSON.stringify(treeOptions)) .pipe( map(this.extract ...

The optimal location to declare a constructor in Typescript

When it comes to adding properties in an Angular component, the placement of these properties in relation to the constructor function can be a topic of discussion. Is it best to declare them before or after the constructor? Which method is better - Method ...

What is the best way to adjust the spacing based on the width of the screen?

Seeking assistance with coding for a website, I have encountered an issue where I need the background to be relative to the user's screen width. However, I am struggling to find the right approach. I have attempted using relative units and media quer ...

What are some strategies for accessing the original values of form components that have not been altered when using ngModel?

I am currently developing a form and I intend to utilize the previous values as "value" in the form. By employing ngModel dynamically, I am able to change some properties. However, I have encountered an issue where the field that remains unchanged by the u ...

My Horizontal Drop Down Menu won't stay still, how can I make it stop moving?

I'm a beginner with dropdown menus and I'm struggling to prevent my dropdown menu from expanding and pushing the main buttons. I think it's related to a positioning adjustment, but I can't pinpoint where or what it is. Here is the link ...

Exploring the combination of Angular and Redux on windows devices

Upon running ng serve, I encountered the following error: The class NgRedux<RootState> has been incorrectly implemented as interface ObservableStore<RootState>. The property [Symbol.observable] is missing in type NgRedux<RootState> but i ...

Guide on implementing JWT authentication in API using Nebular Auth

I have implemented Nebular auth for my Angular application. I am trying to include a token in the header when a user logs in. Below is the API response: { "status": 0, "message": null, "data": { "type": &qu ...

Using Angular 2 to Encode a File into a Base64 Format

I am trying to utilize Angular2 and interact with a webservice that retrieves files using base64 string. After successfully fetching the file data through http, I have attempted various methods but unable to convert it into base64 format. It's quite ...

Encountering a CORS error after deploying an Angular and Spring Boot application on Heroku

Currently facing challenges with an app due to CORS issues. It functions perfectly locally, but once deployed, an error occurs. Access to XMLHttpRequest at 'https://portafolioback.herokuapp.com/portafolio/version1/post/all' from the origin &apos ...

Centering text underneath bootstrap image design

After trying various methods, I still couldn't get the text to display directly below my images in the center. Below is the code I attempted: <div class="our_partners"> <div class="container"> <div class="row"> ...

Angular2 calendar and time selector

Having trouble setting up a date and time picker for my angular2 app. Can anyone provide assistance with this? I've experimented with the following methods: Ng2-datetime: I added it to the main app.module file: import { NKDatetimeModule } from &ap ...

Exploring jQuery's ability to retrieve CSS values

Is there a way to use jQuery to read a specific CSS value from a class? The situation is as follows: HTML: <div class="box"></div> CSS: .box { margin-top: 100px; } I want to determine if the .box class has a margin-top of 100px in order t ...

Angular - Highlight a section of a string variable

Is there a way to apply bold formatting to part of a string assigned to a variable? I attempted the following: boldTxt = 'bold' message = 'this text should be ' + this.boldTxt.toUpperCase().bold() ; However, the HTML output is: thi ...

Storing various checkbox values into a database

I have a form with checkboxes that I need to submit to an API for database storage. This is the city.page.html <ion-item *ngFor="let city of cities;"> <ion-checkbox [(ngModel)]="city.id" ></ion-checkbox> <i ...

What is the best approach for managing errors between Node.js and Angular 2?

I have a simple task at hand. Let's consider a scenario where a user can submit news through a form that has two fields: title and content. The title field is required, which can be validated both on the client side and server side using the following ...

Expanding and shrinking div elements in Angular with sliding effects on other divs

Hello, I am just starting with angular and angular animations, and I have encountered a problem. Here is the html code that I am working with: <div class="main"> <div class="left" *ngIf="showLeftSide" [@slideInOutLeft]></div> <di ...

Error in Angular SSR: Build failed due to project reference without "composite" setting set to true

Currently facing an issue while developing an Angular App with SSR. When using npm run build:ssr, the following errors are displayed: ERROR in [...]/tsconfig.json [tsl] ERROR TS6306: Referenced project '[...]/tsconfig.app.json' must have se ...