Using the Style and CSS Loaders

In notebook:
FrontEndMasters Webpack Deep Dive
Created at:
2017-01-02
Updated:
2017-01-02
Tags:
Webpack libraries JavaScript
FEM/01.5-css branch

You need to install these packages
    "devDependencies": {
    "babel-core": "6.13.2",
    ...
    // 1. ++++
    "css-loader": "0.23.1",
    ...
    "rimraf": "2.5.4",
    // 2. ++++
    "style-loader": "0.13.1",
    "webpack": "2.1.0-beta.20",
    "webpack-config-utils": "2.0.0",
    "webpack-dev-server": "2.1.0-beta.0",
    "webpack-validator": "2.2.7"
  },
Then, in Webpack
  // ****   webpack.config.babel.js   ****

devtool: ifProd('source-map', 'eval'),
module: {
  loaders: [
    {test: /\.js$/, loaders: ['babel'], exclude: /node_modules/},
    // 1. ++++ add the style, css loaders
    // first style then css
    {test: /\.css$/, loaders: ['style', 'css']},
  ],
},

The style​ loader injects it into the DOM

The loaders run from right to left

The style loader should come before the css loader. 

For CSS you usually don't exclude node_modules

Require the CSS in app.js

  // ****   app.js    ****

// 1. ++++
require('todomvc-app-css/index.css')

var View = require('./view')
var helpers = require('./helpers')
...
Now the ​<style>​ is injected in the DOM.

What about performance???

The CSS is injected at runtime! 
Also, since the CSS is in the JavaScript file which is added at the end of the DOM we get the flash of unstyled content. 

Critical CSS

The best way is to add the critical CSS to the ​<head>​. 

For now, he just puts the bundle.js in the ​<head>​.