Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I include css from npm in Angular2

Tags:

angular

This has been surprisingly hard to find an answer to, please point out if I'm not searching right and this is a duplicate question.

I have an Angular2 (2.0.0-beta.14) app and am having issues including a 3rd party css file. I've downloaded materialize-css via npm and I can see the file is at node_modules/materialize-css/bin/materialize.css.

I would like this css file to be visible to my entire application.

At the highest level, I've tried including it in my index.html head section <link rel="stylesheet" href="./node_modules/materialize-css/bin/materialize.css" media="screen">, but can't figure out where it's being served or even if it's being served.

At a lower level, I've tried defining it in the styleUrls token of the app initiation.

@Component({
  selector: 'myApp',
  providers: [],
  pipes: [],
  directives: [ROUTER_DIRECTIVES],
  templateUrl: 'app/henna.html',
  styleUrls: ['materialize.css']
})

I've tried various different styleUrls trying to find the file, but it seems the problem might be that the file is not accessible.

Please let me know any more info that is needed to help, this is my first application that I've used Angular2.

like image 358
awwester Avatar asked Apr 15 '16 15:04

awwester


1 Answers

This was an issue with webpack not bundling my files how I was expecting (I had never used webpack before). I needed to install the correct webpack loaders for css and font files, import materialize, and then the files were being included.

After installing the correct loaders (npm install css-loader npm install file-loader), in webpack.config.js I needed to modify the module object.

module: {
    loaders: [
      { test: /\.ts$/, loader: 'awesome-typescript-loader' },
      { test: /\.css$/, loader: "style-loader!css-loader" },
      { test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/, loader : 'file-loader'},
    ]
  }

in the vendor.js file, I needed to import the materialize js and css

import 'materialize-css/bin/materialize.css'
import 'materialize-css/bin/materialize.js'
like image 157
awwester Avatar answered Oct 19 '22 22:10

awwester