Home » Angular 2 » Adding CSS and JavaScript to an Angular 2 CLI Project

Adding CSS and JavaScript to an Angular 2 CLI Project

In the last post, we looked at how to create an Angular 2 project using the Angular CLI.  Today we want to look at how to manage CSS and JavaScript to our Angular 2 CLI project.

image

Adding CSS and JavaScript

The temptation is to add the external files directly to your index.html file.  But if you do this, the files won’t get bundled.  This wouldn’t be horrible, but it isn’t the Angular 2 way. What we ultimately want to end up with is code that we can ship all as one unit.

If you’ve already done a build, you should have a folder named “dist” with all the files you need to run your application.  What we want to end up with is ALL of the files we need for our application in that directory all bundled and minified.

As an example of how to do this, we will add Bootstrap 3 to our project.

Install

The first step is to add Bootstrap to our project.

npm install bootstrap --save-dev

Bootstrap will also need jQuery installed so we will add that next.

npm install jquery --save-dev

Include

And to tell the CLI that we want these files installed, we will open the angular-cli.json file and look for the apps.styles and apps.scripts section

      "styles": [
        "styles.css"
      ],
      "scripts": [],

 

And you will modify it to look like this:

      "styles": [
        "../node_modules/bootstrap/dist/css/bootstrap.css",
        "styles.css"
      ],
      "scripts": [
        "../node_modules/jquery/dist/jquery.js",
        "../node_modules/bootstrap/dist/js/bootstrap.js"
      ],

 

Notice that we are relative referencing node_modules from the “src” directory, not the directory the angular-cli.json file is in.

Use

Any CSS files you want to add that you won’t be referencing from your modules directly, and any javascript files that you won’t be importing into your TypeScript files go in this section.  When you compile, they become part of the bundles.  To prove this, we will modify the app.component.html file located in “src/app”

<nav class="navbar navbar-default">
  <div class="container">
    <div class="navbar-header">
       <div class="navbar-brand">
           Getting Started With Angular 2 App
        </div>
    </div>
  </div>
</nav>
<div class="container">
  <h1>
    {{title}}
  </h1>
</div>

 

And now when you build and run the web application, you should see that it is styles using Bootstrap.

Application Level Styles

One of the things you may have noticed in the discussion above is that styles.css was already included in our angular-cli.json file.  This is where you add style information that is relevant to the entire application.

And so far, this is what you would expect.  But Angular 2 takes styling to the next level.

Component Styles

If you’ve been doing any web development at all for any length of time, you may have noticed that you need to be careful about how you apply styles to components within your application because if you aren’t, the style information will “leak” into other components.  Typically, the way I’ve gotten around this is by creating a unique scope around the component so that I can include that scope in my CSS.

In Angular 2, Angular does that work for us.

You see, you can also add style information in your components.  If you open the existing app/app.component.ts file, you will notice that there is both a templateUrl and a styleUrls attribute in the @Component() metadata section.  In the styleUrls property you can specify a list of relative URLs of CSS files to include.

If we include CSS information in the CSS files, you will see that when we render the page, the CSS gets rewritten so that the CSS is scoped to the component.  In fact, if you try to style a component that is a child of the component using the parent’s CSS file, it won’t work.  This is why we can’t just include the application level CSS in the top level component and instead have to put it in a CSS file that we include in our angular-cli.json file.

Application Level JavaScript

The standard way of including JavaScript as part of your application is by using the import keyword.  When the Angular CLI compiles the code, it looks for all the imports and bundles all the JavaScript together.  So, you might wonder why we need a scripts block in our angular-cli.json file.

One reason is because when we build the code for production, the CLI removes any code from the bundle that isn’t being used.  If you need JavaScript code to be included that the compiler would not be able to tell you are using, you must include it in some other way.  In the case above, even if we did an import of the jQuery and bootstrap code, the CLI would never be able to detect that we are actually using it.

It’s All JavaScript

One final note about how Angular works.  While you and I are coding CSS and HTML, when these files get compiled into our bundles, they all end up as JavaScript.  This might seem inefficient.  We’ve been told for years, “Don’t render HTML using JavaScript.”  But, the reason we’ve been told that is because most of us render HTML with JavaScript in a very inefficient way.

But, because Angular has implemented smart change detection, it is more efficient to render the HTML using JavaScript.  That nice template you created is going to end up as JavaScript.  Don’t go looking for it as a separate file that Angular is making an AJAX call to suck into your application.  It gets bundled in with all your other JavaScript.

And the same thing happens with all your CSS.  Angular 2 renders that all into the HEAD section of your HTML using JavaScript.  If you open development tools, you will see several STYLE elements.  If you open them up and look, you’ll see renditions of the CSS from all over your application.

 

Other post in Angular 2
Summary
Adding CSS and JavaScript to an Angular 2 CLI Project
Article Name
Adding CSS and JavaScript to an Angular 2 CLI Project
Description
Looking at the various ways of adding CSS and JavaScript to an Angular 2 CLI Project
Author
DMB Consulting, LLC

About Dave Bush

Dave Bush is a Full Stack ASP.NET developer focusing on ASP.NET, C#, Node.js, JavaScript, HTML, CSS, BootStrap, and Angular.JS. Does your team need additional help in any of the above? Contact Dave today.

Leave a Reply

11 Comments on "Adding CSS and JavaScript to an Angular 2 CLI Project"

Notify of
avatar
Sort by:   newest | oldest | most voted
trackback

[…] Adding CSS and JavaScript to an Angular 2 CLI Project (Dave M. Bush) […]

trackback

[…] Adding CSS and JavaScript to an Angular CLI Project […]

Amy Blankenship
Guest

When you need to debug CSS and it hasn’t been turned into JavaScript first, if you inspect the element in the browser it tells you what CSS file(s) have styles that affect the element, and where in the css file each style is. Is there a map or something that you can use to simulate this effect in an Angular CLI project? If not, I think that this is not going to be workable to develop projects in.

Dave Bush
Guest

Yes, there are map files for the typescript and the CSS (and even LESS and SASS if you use that).

I’m currently doing a lot of CSS work for the company I work at and I am not having any issues that I don’t normally have doing it in an old school way.

Amy Blankenship
Guest

How do you get it to be used? When I made some of the changes from the “Adding CSS and JavaScript” tutorial and inspected the container div, it didn’t show where the styles were coming from the Bootstrap css.

Dave Bush
Guest
OK. Sorry. I answered while I was making my dinner and didn’t spend enough time with this the first time around. While it does produce source maps, they are to the JavaScript that inserts the CSS into your page. Not what you had in mind. So, the answer I gave was technically correct but wasn’t the answer to the question you were asking. Agan, I’m sorry. However, the CSS that does show up in the elements tab does show you the exact CSS for the element. So we can see exactly what CSS rule to modify in chrome and go… Read more »
Amy Blankenship
Guest
I wouldn’t actually care about Bootstrap CSS, I was just poking around in the minimal example and happened to notice that there was no way to know it was even coming from Bootstrap. If you imagine a situation where you’re overriding some of the Bootstrap styles with your own styles in a global style sheet and then you could have a further refinement in a component style sheet, “going looking for it” becomes really daunting. I don’t personally use LESS or SASS. Like the Bootstrap CSS, I feel that if you understand CSS well enough to use these tools effectively,… Read more »
Dave Bush
Guest

You will be happy to know that the Angular CLI provides a flag to keep the CSS as CSS rather than turning it into JavaScript

ng serve —extract-css

obviously
Guest

I notice that when you install jquery (lower-case makes a BIG difference to npm) and bootstrap via npm, you specify –save-dev (a.k.a. -D ) instead of –save (a.k.a. -S ).

Why is that?

Don’t we need to deploy them eventually (production environment)? That would normally mean jQuery and Boostrap would wind up in the “dependencies” section of package.json, not the “devDependencies” section.

Or am I missing some “magic” that causes Webpack to figure out this out because of how the normally empty “styles” and “scripts” arrays of angular-cli.json are populated as you suggest in the article?

Dave Bush
Guest

webpack and the cli bundle all the files in the styles and script tags and insert them into the html so, no, you won’t need them at runtime

Manzer
Guest

how to include our own custom javscript files in angular2-cli-webpack-project

wpDiscuz