Exercise: Extracting CSS Part 2
The internal flow of extracting the CSS
// loaders take an input and return some output
// can be text, code, an object etc
{
test: /\.css$/,
// this loader returns as text
// this also creates the css bundle file
// and removes from the main bundle
loader: ExtractTextPlugin.extract({
fallbackLoader: 'style',
// this loader processes the CSS
loader: 'css',
})
...
// then
plugins: removeEmpty([
new ProgressBarPlugin(),
// saves out the file and injects the link tag
new ExtractTextPlugin(ifProd('styles.[name].[chunkhash].css', 'styles.[name].css')),
ifProd(new InlineManifestWebpackPlugin()),
ifProd(new webpack.optimize.CommonsChunkPlugin({
names: ['vendor', 'manifest'],
})),
Q&A: What's the point of using Webpack for CSS as opposed to Grunt or Gulp?
Explains the concept of coupling together everything (markup, styles, JavaScript) that a component needs to function. First html (React), then CSS. Now you have everything in one place. You can couple these dependencies (html, JavaScript, CSS) together, and make analysis on them, etc.
Q&A: Does the html, JavaScript get associated together other than just putting them in Webpack?
CSS modules.
CSS modules is one solution to enforce this coupling.
Need to set your plugin like this:
loader: 'css'
// ↓
loader: {
name: 'css',
query: {
modules: true
}
}
Now, you can import your CSS into your module (like app.js) like this
// **** app.js ****
import 'todomvc-app-css/index.css'
// 1. ++++ import just toggleGraph
import {toggleGraph} from './app.css'
import {$on} from './helpers'
import {updateTodo} from './todo'
import toggleGraph from './graph'
export function onLoad() { // eslint-disable-line import/prefer-default-export
updateTodo()
const toggleGraphButton = document.querySelector('.toggle-graph')
$on(
toggleGraphButton,
'click',
() => {
const active = toggleGraph()
if (active) {
// 2. ++++ then use it here like so
toggleGraphButton.classList.add(toggleGraph)
} else {
toggleGraphButton.classList.remove('active')
}
},
)
}
He prefers now CSS in JavaScript, but otherwise you can do CSS modules as above. Q&A: Can we have to extractTextPlugins for both SASS and CSS?
Explains that you should not have to loaders whose
test
are the same, but then rather create an array. It would look something like this:
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({
fallbackLoader: 'style',
loader: 'css',
})
},
{
test: /\.sass$/,
loader: ExtractTextPlugin.extract({
fallbackLoader: 'style',
loaders: ['css', 'sass'],
})
},