5

According to the official webapck documentation, webpack imports specified CSS files into your JavaScript module using a loader called css-loader.

What good does this process do? How can you just not go with the old school way of linking a CSS file to your html using the link tag?

Hooey
  • 85
  • 1
  • 8

1 Answers1

1

I will give you a good exemple of a scenario where linking the css is not possible.

If you are developing a ASP.NET Core MVC application, and wanna use some css from the node_modules folder, it will be not possible to resolve the path to that folder. This happens because the ASP.NET serves files only from the wwwroot directory.

Because of that, you need a build system just like webpack.

With a css loader in webpack, it will check for every css reference in the js/ts files provided as entries and will generate another css file in the output directory (usually inside wwwroot). Take a look at this example:

entry: {
vendor: [
    '@angular/animations',
    '@angular/cdk',
    '@angular/material',
    '@angular/common',
    '@angular/compiler',
    '@angular/core',
    '@angular/flex-layout',
    '@angular/forms',
    '@angular/http',
    '@angular/platform-browser',
    '@angular/platform-browser-dynamic',
    '@angular/router',
    '@angular/material/prebuilt-themes/pink-bluegrey.css',
    'es6-shim',
    'es6-promise',
    'event-source-polyfill',
    'jquery',
    'zone.js',
    'jwt-decode'
]}

Here I added a theme css for angular material. Note that the css is inside the vendor js/ts bundle. The css loader will extract the css from there and generate a css file with the same name of the bundle. The generated file, placed on the wwwroot folder, will be the one that you will reference in your index.html (assuming it is a SPA application like in this example).

Of course, you can just copy the css file from the node_modules folder, and put it in the wwwroot directory so that you will be able to link it. But that approach is fragile because when another version of the css is available and you wan't the up to date version, you will have to update the packages and copy the files all over again. So, why not automate it?

Jackson Mourão
  • 1,041
  • 10
  • 19