Check out our Angular Book Series.

Why aren't Styles working with my Angular 6 Build?

I was working on an Angular 6 project that recently ran into a problem. All our styles were messed up when we created a production build. There are a lot of complaints about it here.

There seem to be two solutions that work for us and I'll go over both of them.

Move the Styles

The first solution is to remove all your style imports from the Angular.json. Then add them back into the main styles.scss using @imports. So, my Angular CLI styles looks like this:


"styles": [
"src/styles.scss",
"node_modules/bootstrap/dist/css/bootstrap.css",
"node_modules/@swimlane/ngx-datatable/release/assets/icons.css",
"node_modules/@swimlane/ngx-datatable/release/themes/material.css"
],

Open up the styles.scss and add them as imports:


@import "../node_modules/bootstrap/dist/css/bootstrap.css";
@import "../node_modules/@swimlane/ngx-datatable/release/assets/icons.css";
@import "../node_modules/@swimlane/ngx-datatable/release/themes/material.css";

The styles would now change to this:


"styles": [
"src/styles.scss",
],

This worked. I actually think I like putting the styles in the main styles.scss instead of the Angular.json. I prefer to stay out of the Angular.json as much as possible.

Change Extract CSS Value

The second option, and the one in which we chose to do for this project, was to change the extractCss value from true to false. Inside your Angular.json find the value:


"extractCss":true

You'll find the value at projects.architect.build.configuration.product.extractCss

Change it to:


"extractCss":false

Now open up your package.json and find the build prod command:


"prod":"ng build"

Add the build-optimizer argument:


"prod":"ng build --build-optimizer"

This should address the issue.

When you create a normal build, the styles are minimized into a JavaScript file--styles.js--and then loaded on demand by Angular as needed. When you use extractCSS, the files are combined into a single CSS file instead of being created in a js file. Part of the minimization process seems to be screwing up the order that files are compressed, which of course affects the final CSS and why our styles were not showing up correctly.

This caused a few grumblings among my team about how borked Angular CLI is, but I still enjoy working with it.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version 5.9.2.002.