user1675891
user1675891

Reputation:

Can't create CSS from SASS using Webpack

I've created a minimal file global.sass with the following contents (taken from here).

$font-stack:    Helvetica, sans-serif
$primary-color: #333
body
  font: 100% $font-stack
  color: $primary-color

In my webpack.config.js I have added the following loaders to module section (the second one taken from here as sugested on Webpack's page here).

module: {
  loaders: [
    { test: /\.js$/, loader: "babel", exclude: /node_modules/ },
    { test: /\.sass$/, loader: "sass-loader", exclude: /node_modules/ }
  ]
},

In my gullible hopes I thought that running webpack --progress would produce a CSS file but apparently, nothing like that occurs. I only get a new version of bundle.js but the contents of the global.sass file aren't anywhere in it. No CSS file's produced at all.

Upvotes: 1

Views: 106

Answers (1)

luiscrjr
luiscrjr

Reputation: 7278

First of all, you need to require somewhere your style file.

For instance, if your entry file is main.js you can have something like this:

require('./global.sass');
/* or, if you're using es6 import:

    import css from './global.sass'; 
*/

To clarify the process a bit: sass-loader process the .sass files and converts it to a valid css file (in memory, let's say so). Then, you'll have to chain (backwards) loaders to finally add the styles to your page:

A default configuration would be:

loaders: [
    /* ... */
    { 
        test: /\.sass$/, 
        loaders: ["style-loader", "css-loader", "sass-loader"], 
        exclude: /node_modules/ 
    }
    /* ... */
]

where css-loader resolves a CSS file and style-loader add a <style> tag at the bottom of your <head> with your style.

Before running that, make sure you've installed those packages:

npm i css-loader style-loader sass-loader node-sass --save-dev

You can, however, extract all your styles into a separated css file using the popular extract text plugin.

We can say, then, to summarize, that webpack does not generate a separated css file due to the style-loader (that adds a style tag to your DOM), unless you use the extract text plugin (very common in productions build).

Upvotes: 1

Related Questions