Dean Gibson Dean Gibson - 6 months ago 55
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:

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

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

  • style-loader

  • css-loader

  • sass-loader (also installed
    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
in the root of my directory it looks like it works. But the
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
of course...


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:


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

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

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.