Giter VIP home page Giter VIP logo

webpack-scss-sass-file's Introduction

Webpack Sass / Scss compiling to separate file

Webpack is an amazing tool for transpiling and bundling JavaScript, but it can also take care of compiling Sass or Scss to static files.

get the code on github

I came across this issue while developing a prototype and not a single page app, that I needed to have a .scss file include some other files and output a .css file. I didn't need inlined and scoped CSS like one would probably do with a single page app.

This took me surprisingly long to figure this out, mostly because there is a lot of varying information out there and not a lot of good examples that work with the up to date versions of webpack 2 RC 4 and the ExtractTextPlugin.

First of all, I recommend you globally install a recent webpack version:

npm -g install [email protected]

Inside your project you need to install the following dependencies, remember to append the --save flag if you want them to be written to your package.json:

npm install css-loader node-sass sass-loader [email protected]

Now let's say we have a project structure for a simple one-page that looks like the following (identical to the example project):

├── app.js
├── package.json
├── scss
│   ├── about
│   │   └── about.scss
│   └── main.scss
├── webpack.config.js
  • app.js contains all our cool JavaScript code
  • package.json defines our dependencies
  • scss/main.scss is our scss / sass entry point
  • webpack.config.js is our config that tells webpack what to do

If you have cloned the example repository, after running the build with webpack it should look like the following:

├── app.js
├── dist
│   ├── bundle.js
│   └── main.bundle.css
├── package.json
├── scss
│   ├── about
│   │   └── about.scss
│   └── main.scss
├── webpack.config.js

Note: Frequently developers use npm run dev or npm run build to execute the webpack command.

Notice that the directory dist including the files bundle.js and main.bundle.css have been added. The latter contains the compiled SCSS from main.scss and about.scss.

Webpack SCSS / SASS config

Typically webpack processes everything in an input file and what ever is required by that file or other files that are required from there. It builds a tree of requirements, scoops up all the JavaScript and other resources and compiles them for you. If you want to just have it look for a file, we need to use the ExtractTextPlugin to process it.

Have a look at the config for this project below:

var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
  entry: ['./app.js', './scss/main.scss'],
  output: {
    filename: 'dist/bundle.js'
  },
  module: {

    rules: [
      /*
      your other rules for JavaScript transpiling go in here
      */
      { // regular css files
        test: /\.css$/,
        loader: ExtractTextPlugin.extract({
          loader: 'css-loader?importLoaders=1',
        }),
      },
      { // sass / scss loader for webpack
        test: /\.(sass|scss)$/,
        loader: ExtractTextPlugin.extract(['css-loader', 'sass-loader'])
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin({ // define where to save the file
      filename: 'dist/[name].bundle.css',
      allChunks: true,
    }),
  ],
};

The config that enables us to compile SCSS/SASS from a file instead of requiring it in our JavaScript source is the loaders that refer to ExtractTextPlugin and the plugin that specifies where to write the file.

Also note that in our entry points, we specify that ./scss/main.scss should be read and then run through the rules (in this case .scss would match).

Transpiled SCSS file

Congratulations, now our .scss files that used to look like this:

main.scss

// include another .scss file from a sub-directory
@import './about/about.scss';

body {
    a {
        color: magenta;
    }
}

about/about.scss

body {
    p {
        line-height: 1.5;
    }
}

Should be transpiled into a plain css file:

body p {
  line-height: 1.5; }

body a {
  color: magenta; }

Thank you so much for reading this post, I hope it was useful to you! Consider following me on twitter, feedly or instagram!

If anything doesn't work, please leave a comment and I'll have a look!

webpack-scss-sass-file's People

Contributors

austinpickett avatar jonathanmh avatar marabesi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

webpack-scss-sass-file's Issues

add bootstrap to project?

Hi, How would you add bootstrap to the project if you want to add just the css file?

You add it to packages.json as a dependency, npm update and then you use the node_modules/boostrap/dist/bootstrap.min.css to include the file? If yes, where (in what file and how) do I include it?

Is there a easier way?

webpack rules

Hellos @JonathanMH ,

thank you very much for this repo. I've had the same problem and this repo was incredibly helpful.

Though, I could understand why do we need to have two loaders.

    { // regular css files
        test: /\.css$/,
        loader: ExtractTextPlugin.extract({
          loader: 'css-loader?importLoaders=1',
        }),
      },
      { // sass / scss loader for webpack
        test: /\.(sass|scss)$/,
        loader: ExtractTextPlugin.extract(['css-loader', 'sass-loader'])
      }

The sass is the loaders which will be responsible to compile the sass, right?

What about the css loader? Is it to create the .css file only?

Modifying JS file recompiles SCSS as well.

Hello there,

First I'd like to thank you for the great config file that does pretty much exactly what I want to do. One thing I noticed is while I'm watching, if I modify a JS file, the SCSS file gets recompiled as well.

This is the command I ran:
webpack --progress --colors --watch --env --profile

This is what I get when I modify a JS file.
image

However, modifying the SCSS file is completely fine, and only recompiles the styles:
image

I was wondering if it were possible to only recompile JS if I modify the JS file.

Your help is appreciated. Thank you!

ERROR in multi ./app.js ./scss/main.scss build

I updated package.json as

"scripts": {
    "build": "webpack build"
  },

After npm run build, I got this error

ERROR in multi ./app.js ./scss/main.scss build
Module not found: Error: Can't resolve 'build' in '/Users/linwilliam/Documents/Projects/develop/webpack-scss-sass-file-master'
 @ multi ./app.js ./scss/main.scss build
Child extract-text-webpack-plugin:
       [0] ./~/css-loader/lib/css-base.js 1.51 kB {0} [built]
       [1] ./~/css-loader!./~/sass-loader!./scss/main.scss 222 bytes {0} [built]

ExtractTextPlugin fails to compile SCSS

ExtractTextPlugin has changed the syntax of how you require loaders, in addition for css-loader, it requires you to specify style-loader as a fallback.

See: https://github.com/webpack-contrib/extract-text-webpack-plugin#usage

const ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          fallback: "style-loader",
          use: "css-loader"
        })
      }
    ]
  },
  plugins: [
    new ExtractTextPlugin("styles.css"),
  ]
}

How to load url in sass file

Hi Jonathan,
Thanks for the code.
I included the property background: url('./images/bg.jpg'); in my sass file.
Can you please help with issue.
What is the best way to load url in sass file.

How would you add multiple loaders with individual options for each one?

Here's where I am:

module: {
    rules: [
      {
        test: /\.s[ac]ss$/,
        use: ExtractTextPlugin.extract({
          use: {
            loader: "sass-loader",
            options: {
              sourceMap: true,
              includePath: "./node_modules/bootstrap-sass/assets/stylesheets"
            }
          },
        })
      }
    ]
  },

But with this pattern in mind, how do you add more loaders ( we need css-loader, sass-loader, postcss-loader ..) but with adding more options for every loader individually?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.