Dean Gibson Dean Gibson - 3 months ago 30
Node.js Question

Compile Scss with Webpack

I'm still trying to wrap my head around webpack, and coming from Gulp it's quite confusing. My project structure looks like:

./root
-- src
-- styles.scss
-- bin
-- node_modules
-- webpack.config.js


So just something super simple, I want to compile the
styles.scss
in the
src
directory and output it to the
bin
directory. I installed the following loaders:


  • style-loader

  • css-loader

  • sass-loader (also installed
    node_sass
    as a dependency)



Now I know I'm not grasping something very fundamental of Webpack here but here's my webpack.config.js:

module.exports = {
entry: './src/styles.scss',
output: {
path: './bin',
filename: 'styles.css'
},
module: {
loaders: [
{
test: /\.scss$/,
loaders: ["style", "css", "sass"]
}
]
}
};


When I run
webpack
in the root of my directory it looks like it works. But the
styles.css
file looks like it contains a bunch of JavaScript code. So I don't understand that and need some clarity. I'm vaguely guessing that you can't use webpack if you don't have any JavaScript files in your project (besides
webpack.config.js
of course...

Answer

I am by far no webpack expert, but to my understanding, this is exactly what webpack is supposed to do, according to it's own documentation:

Loaders

webpack can only process JavaScript natively, but loaders are used to transform other resources into JavaScript. [...]

What this means is, even if you only include SCSS-Files, webpack will convert them into a JavaScript-File, which can then be included just as any other JS-File.

For example, if you changed your styles.css into styles.js, you would call it in the head of html with

<head>
  ...
  <script type="application/javascript" src="styles.js" charset="utf-8"></script>
  ...
</head>

Despite this, your CSS, although called as and wrapped in JavaScript, will still be correctly treated as CSS.

Why would you want to do this?

Basically to save calls to the server. Webpack gives you the opportunity, to bundle your JS, your [S]CSS and many other things into a single JS-File, which you will be able to fetch with a single call to server, therefore saving lots of round-trip-times. Yet, the browser will interpret all the resources accordingly.