Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import a _global.scss file with Webpack only once, and not in every single .scss file?

Trying to find a way to import a _.global.scss file with my webpack build once, instead of importing it in each .scss file (I have a scss file for each component).

The only possible solution I found so far, was to use a baggage-loader, but I couldn't make it work.

The loaders in my webpack.config looks like this:

loaders: [{
            test: /\.scss$/,
            loader: "style-loader!raw-loader!sass-loader"
                + "!baggage?"+ path.resolve(__dirname, "./src/_config/_global.scss")
        }]

Thanks!

like image 755
Dima Feldman Avatar asked Mar 31 '16 16:03

Dima Feldman


1 Answers

You can create a custom loader that will inject an @import statement in all of your scss files.

Here's a webpack.config.js file for that:

var path = require('path');

module.exports = {
  entry: './src/app.js',
  output: {
    filename: 'build/bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.scss$/,
        exclude: /node_modules/,
        loader: 'style!css!sass!' + path.resolve('loaders/inject-global-scss') 
      }
    ]
  }
}

This snippet assumes that you have a loaders folder and inside of it, a inject-global-scss.js file.

Here's the contents of this file:

module.exports = function(source) {
  this.cacheable();
  return `@import './src/_config/_global';
    ${source}`;
}

Now, I'm assuming you have a _global.scss file inside the src/_config folder. And that you're using node 5+ because of the string template syntax.

like image 136
thitemple Avatar answered Sep 20 '22 23:09

thitemple