Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import CSS from node_modules in webpack angular2 app

Let's say that we start with the following starter pack: https://github.com/angularclass/angular2-webpack-starter

After npm install and npm run start everything works fine.

I want to add an external css module, for example bootstrap 4's css (and only the css). (I know that bootstrap has a bootstrap-loader, but now I'm asking for general solution, so please think about bootstrap 4 here as it could be any other css module that is available via npm).

I install bootstrap via npm: npm install [email protected] --save

First I thought that it is enough to add import 'bootstrap/dist/css/bootstrap.css'; to the vendor.browser.ts file.

But it isn't.

What should I do to have a proper solution?

Solutions I'm NOT asking for:

  1. "Copy the external css module to the assets folder, and use it from there"
    • I'm looking for a solution that works together with npm package.
  2. "Use bootstrap-loader for webpack"
    • As I described above, I'm looking for a general solution, bootstrap is only an example here.
  3. "Use another stack"
    • I'm looking for a solution in the exact starter pack that I've mentioned above.
like image 250
Burnee Avatar asked Oct 16 '16 15:10

Burnee


People also ask

How do I import CSS into Node<UNK>Modules?

Use an absolute path to import a CSS file from node_modules in React, e.g. import 'bootstrap/dist/css/bootstrap. min. css' . Make sure you have the specific package installed, omit the node_modules directory and start with the package name.


1 Answers

It is possible by using @import '~bootstrap/dist/css/bootstrap.css'; on the styles.css file. (Note the ~)

Edit: How it works - The '~' is an alias set on the webpack config pointing to the assets folder... simple as that..

Edit 2: Example on how to configure webpack with the '~' alias... this should go on the webpack config file (usually webpack.config.js)...

// look for the "resolve" property and add the following...  // you might need to require the asset like '~/bootsrap/...'  resolve: {    alias: {      '~': path.resolve('./node_modules')    }  }
like image 100
Anderson Ivan Witzke Avatar answered Sep 24 '22 17:09

Anderson Ivan Witzke