Search code examples
webpackstylus

Webpack: Can you include a set of global styles used when compiling preprocessed styles with a loader?


I'm not sure if this is possible or not, and can't seem to find anything on it. I've got webpack setup with stylus loaders, allowing the .styl files to be imported in the js modules directly.

The issue I'm facing is that the preprocessor context starts and ends with that single .styl file.

I'd like to be able to define global styles, ex:

// global.styl

$brand-var1 = #000;
$brand-var2 = #FFF;

Which can be relied upon by the individual .styl files imported:

// my-comp.styl

button {
  background-color: $brand-var1;
}

by the js component

// my-comp.js

import './my-comp.styl'
...

I'd like to avoid having to @import or @require the global styles in each and every stylus file which would use it.

Is there any webpack config which would allow me to do this?


Solution

  • Webpack 2: in rules you can pass import option to stylus-loader to load styles globally:

      {
        test: /\.styl$/,
        use: [
          'style-loader',
          'css-loader',
          {
            loader: 'stylus-loader',
            options: {
              import: [
                resolve(__dirname, 'src/styles/global.styl')
              ]
            }
          }
        ],
        exclude: /node_modules/
      }
    

    In webpack I used it this way:

    module.exports = {
      ...,
      stylus: {
        import: [
          path.resolve(__dirname, './src/styles/globals.styl')
        ]
      }
    }