• Stars
    star
    979
  • Rank 45,622 (Top 1.0 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 8 years ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

SASS resources (e.g. variables, mixins etc.) loader for Webpack. Also works with less, post-css, etc.

sass-resources-loader

GitHub Workflow Status npm version license

This loader will load your Sass resources into every required Sass module. So you can use your shared variables, mixins and functions across all Sass styles without manually loading them in each file.

  • Made to work with CSS Modules!
  • This loader is not limited to Sass resources. It supposedly works with less, post-css, etc. per issue 31.
  • Supports Webpack 4
  • Supports Sass @use syntax. You must use Dart Sass (sass, not node-sass npm package). See the hoistUseStatements option.

ShakaCode

If you are looking for help with the development and optimization of your project, ShakaCode can help you to take the reliability and performance of your app to the next level.

If you are a developer interested in working on Ruby on Rails / Rust / TypeScript / ReScript projects, we're hiring!


Installation

Get it via npm:

npm install sass-resources-loader

Usage

Create your file (or files) with resources, which are snippets of Sass that you want available to places like CSS modules Sass:

/* resources.scss */

$section-width: 700px;

@mixin section-mixin {
  margin: 0 auto;
  width: $section-width;
}

Options

Name Type Default Description
resources {String|String[]} undefined Resources to include in files
hoistUseStatements {Boolean} false If true, entry file @use imports will be hoisted. This means that @use statements will go above the inclusion of resources.

Option Examples

resources

Specify resources, contents of which will be prepended to each file.

For example, if variable $my-variable: #fff is in file example/a.scss, specify this file as a resource in your webpack.config.js

{
    loader: 'sass-resources-loader',
    options: {
        resources: 'example/a.scss'
    }
}

to prepend this variable

// Entry file

$my-variable: #fff;

// Entry file's content go here

hoistUseStatements

Tells the compiler if an existing @use statement is found in entry file, it should be hoisted to the top. The reason is that @use must go before most other declarations, except variable declarations, per the docs.

If our entry file has the following content

// Entry file
@use 'my/definitions/file';
@use 'my/other/definitions/file';

// Entry file's contents go here

and our resource file contains this

$my-variable: #fff;

@mixin some-mixin {
    color: #000;
}

then the output, with hoistUseStatements set to true, would be the following. Note that the @use statements are above the inclusion of resources.

// Entry file
@use 'my/definitions/file';
@use 'my/other/definitions/file';

// Resources
$my-variable: #fff;

@mixin some-mixin {
    color: #000;
}

// Rest of entry file's content goes here

You can also use this multi-line syntax:

@use 'config' with (
    $text-color: #FAFAFA
);

See ./test/scss/hoist-multiline.scss for an example.

As mentioned in the docs for Sass @use, you don't need to hoist if your "resources" only contains variable definitions.

If you get the error:

SassError: @use rules must be written before any other rules.

then you need to use the hoistUseStatements: true option.

Tips

  • Do not include anything that will be actually rendered in CSS, because it will be added to every imported Sass file.
  • Avoid using Sass import rules inside resources files as it slows down incremental builds. Add imported files directly in sassResources array in webpack config instead. If you concerned about location of your resources index, you might want to check out the solution outlined in this comment.
  • If you still want to use Sass import rules make sure your paths are relative to the file they defined in (basically, your file with resources), except the ones started with ~ (~ is resolved to node_modules folder).

Apply loader in webpack config (v1.x.x & v2.x.x are supported) and provide path to the file with resources:

/* Webpack@2: webpack.config.js */

module: {
  rules: [
    // Apply loader
    {
      test: /\.scss$/,
      use: [
        'style-loader',
        'css-loader',
        'postcss-loader',
        'sass-loader',
        {
          loader: 'sass-resources-loader',
          options: {
            // Provide path to the file with resources
            resources: './path/to/resources.scss',

            // Or array of paths
            resources: [
              './path/to/vars.scss',
              './path/to/mixins.scss',
              './path/to/functions.scss'
            ]
          },
        },
      ],
    },
  ],
},

/* Webpack@1: webpack.config.js */

module: {
  loaders: [
    // Apply loader
    { test: /\.scss$/, loader: 'style!css!sass!sass-resources' },
  ],
},

// Provide path to the file with resources
sassResources: './path/to/resources.scss',

// Or array of paths
sassResources: ['./path/to/vars.scss', './path/to/mixins.scss'],

NOTE: If webpackConfig.context is not defined, process.cwd() will be used to resolve files with resource.

Now you can use these resources without manually loading them:

/* component.scss */

.section {
  @include section-mixin; // <--- `section-mixin` is defined here
}
import React from 'react';
import css from './component.scss';

// ...

render() {
  return (
    <div className={css.section} />
  );
}

Glob pattern matching

You can specify glob patterns to match all of your files in the same directory.

// Specify a single path
resources: './path/to/resources/**/*.scss', // will match all files in folder and subdirectories
// or an array of paths
resources: [ './path/to/resources/**/*.scss', './path/to/another/**/*.scss' ]

Note that sass-resources-loader will resolve your files in order. If you want your variables to be accessed across all of your mixins you should specify them in first place.

resources: [ './path/to/variables/vars.scss', './path/to/mixins/**/*.scss' ]

Examples and Related Libraries

Example of Webpack 4 Config for Vue

  module: {
    rules: [
      {
        test: /\.vue$/,
        use: 'vue-loader'
      },
      {
        test: /\.css$/,
        use: [
          { loader: 'vue-style-loader' },
          { loader: 'css-loader', options: { sourceMap: true } },
        ]
      },
      {
        test: /\.scss$/,
        use: [
          { loader: 'vue-style-loader' },
          { loader: 'css-loader', options: { sourceMap: true } },
          { loader: 'sass-loader', options: { sourceMap: true } },
          { loader: 'sass-resources-loader',
            options: {
              sourceMap: true,
              resources: [
                resolveFromRootDir('src/styles/variables.scss'),
              ]
            }
          }
        ]
      }
    ]
  }

VueJS webpack template(vue-cli@2)

If you wish to use this loader in the VueJS Webpack template you need to add the following code in build/utils.js after line 42 :

if (loader === 'sass') {
  loaders.push({
    loader: 'sass-resources-loader',
    options: {
      resources: 'path/to/your/file.scss',
    },
  });
}

VueJS webpack template(vue-cli@3)

If you are using vue-cli@3, you need to create a vue.config.js file in your project root (next to package.json). Then, add the following code:

// vue.config.js
module.exports = {
  chainWebpack: config => {
    const oneOfsMap = config.module.rule('scss').oneOfs.store
    oneOfsMap.forEach(item => {
      item
        .use('sass-resources-loader')
        .loader('sass-resources-loader')
        .options({
          // Provide path to the file with resources
          resources: './path/to/resources.scss',

          // Or array of paths
          resources: ['./path/to/vars.scss', './path/to/mixins.scss', './path/to/functions.scss']
        })
        .end()
    })
  }
}

Contributing

This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the code of conduct.

See Contributing to get started.

License

sass-resources-loader is available under MIT. See LICENSE for more details.

Supporters

JetBrains ScoutAPM
BrowserStack Rails Autoscale Honeybadger

The following companies support our open source projects, and ShakaCode uses their products!

More Repositories

1

react_on_rails

Integration of React + Webpack + Rails + rails/webpacker including server-side rendering of React, enabling a better developer experience and faster client performance.
Ruby
5,066
star
2

react-webpack-rails-tutorial

Example of integration of Rails, react, redux, using the react_on_rails gem, webpack, enabling the es7 and jsx transpilers, and node integration. And React Native! Live Demo:
Ruby
1,714
star
3

bootstrap-loader

Load Bootstrap styles and scripts in your Webpack bundle
JavaScript
1,024
star
4

cypress-on-rails

Use cypress.io or playwright.dev with your rails application
HTML
406
star
5

shakapacker

Use Webpack to manage app-like JavaScript modules in Rails
Ruby
390
star
6

fat-code-refactoring-techniques

Code samples for RailsConf 2014 on Fat Code Refactoring
JavaScript
289
star
7

re-formality

Form validation tool for reason-react
Reason
245
star
8

bootstrap-sass-loader

Webpack Loader for the Sass version Twitter Bootstrap
JavaScript
118
star
9

rescript-dnd

Drag-n-drop for @rescript/react
ReScript
115
star
10

rescript-classnames

Reimplementation of classnames in ReScript
ReScript
110
star
11

rescript-logger

Logging implementation for ReScript
ReScript
107
star
12

react_on_rails_demo_ssr_hmr

react_on_rails tutorial demonstrating SSR, HMR fast refresh, and Typescript based on the rails/webpacker webpack setup
Ruby
86
star
13

font-awesome-loader

Webpack Loader for Font Awesome Using Sass
JavaScript
47
star
14

webpacker_lite

Slimmed down version of Webpacker with only the asset helpers optimized for, but not requiring, React on Rails
Ruby
46
star
15

mirror-creator

One more way to create an object with values equal to its key names
JavaScript
43
star
16

rescript-debounce

Debounce for ReScript
ReScript
42
star
17

steward

Task runner and process manager for Rust
Rust
41
star
18

control-plane-flow

The power of Kubernetes with the ease of Heroku! Our playbook for migrating from Heroku to Control Plane, controlplane.com, and CPL CLI source
Ruby
37
star
19

reactrails-react-native-client

This repository is for a react-native client to the https://www.reactrails.com/, source at https://github.com/shakacode/react-webpack-rails-tutorial/.
JavaScript
30
star
20

redux-tree

An alternative way to compose Redux reducers
JavaScript
23
star
21

rust-rescript-demo

Rust
22
star
22

messagebus

Message bus - enables async communication between different parts of application using messages
Rust
22
star
23

redux-interactions

Composing UI as a set of interactions
21
star
24

ssr-rs

Server-Side Rendering for Rust web servers using Node.js
Rust
20
star
25

bootstrap-sass-loader-example

Example of using the bootstrap-sass-loder to load the Sass version of Twitter Bootstrap using Webpack
JavaScript
16
star
26

style-guide-javascript

ShakaCode's JavaScript Style Guide (Also see our Ruby one: https://github.com/shakacode/style-guide-ruby)
JavaScript
15
star
27

jstreamer

Ruby
12
star
28

justerror

Extension to `thiserror` that helps reduce the amount of handwriting
Rust
12
star
29

react-validation-layer

An opinionated form validation tool for React apps
JavaScript
11
star
30

rescript-react-on-rails

BuckleScript bindings to react-on-rails
ReScript
8
star
31

todos-react-native-redux

Todos app with React Native and Redux
JavaScript
7
star
32

rescript-react-on-rails-example

Example of https://rescript-lang.org/ with React on Rails
Ruby
7
star
33

conform

Macro to transform struct string fields in place
Rust
7
star
34

rescript-first-class-modules-usage

CSS
6
star
35

rescript-throttle

Throttle for ReScript
ReScript
5
star
36

webpacker-examples

Ruby
5
star
37

package_json

Ruby
4
star
38

react_on_rails-with-webpacker

Prototype of webpacker integration
Ruby
4
star
39

use-ssr-computation.macro

A babel macro for reducing initial bundle-size of Apps with React SSR. Uses conditional compilation to make computations server-side and pass the results to the client.
TypeScript
4
star
40

react_on_rails-generator-results

Results of running different react_on_rails generators. See https://github.com/shakacode/react_on_rails
4
star
41

vosk-rs

Rust
3
star
42

react-starter-kit-with-bootstrap-loader

JavaScript
3
star
43

react_on_rails-generator-results-pre-0

Ruby
2
star
44

js-promises-testing

JavaScript
2
star
45

react-on-rails-demo

Example of using the generator for React on Rails
Ruby
2
star
46

uber_task

Ruby
2
star
47

node-webpack-async-example

Simple example of setting up node with webpack
JavaScript
2
star
48

egghead-add-redux-component-to-react-on-rails

Source for Egghead lesson: Add Redux State Management to a React on Rails Project
Ruby
1
star
49

reactrails-in-reagent

Test of converting reactrails example to reagent
1
star
50

rails-tutorial-with-react-on-rails

Adding React on Rails to the Rails Tutorial
Ruby
1
star
51

.github

1
star
52

react_on_rails-test-new-redux-generation

Testing out a different redux generation. See https://github.com/shakacode/react_on_rails/pull/584
Ruby
1
star
53

yardi

Yet Another Rust Dependency Injector
Rust
1
star
54

old-react-on-rails-examples

Various example apps for React on Rails, outdated
JavaScript
1
star
55

v8-demo

React on Rails v8 Usage of the basic generator and a "generator function example"
Ruby
1
star
56

docker-ci

docker container that runs all test and linting against app
Ruby
1
star
57

react-rails-webpacker-resources

1
star
58

sass-rel-paths-issue

JavaScript
1
star
59

reactrails-in-om-next-example

Test of converting reactrails example to om-next
1
star
60

homebrew-brew

Ruby
1
star
61

zone-helper

Swift
1
star
62

react_on_rails-update-webpack-v2

Updating the default React on Rails 6.6.0 redux installation to use Webpack v2 plus adding eslint.
Ruby
1
star
63

shakacode-website

Public website and blog
HTML
1
star
64

react-native-image-zoom-slider

JavaScript
1
star
65

derive-from-one

Automatically generates `From` impls so you don't have to
Rust
1
star
66

rescript-on-rails-example

A sample application using Rescript and React on Rails.
Ruby
1
star