What’s the module pattern?
“Modules are an integral piece of any robust application’s architecture and typically help in keeping the units of code for a project both cleanly separated and organized.”
So in other words a module defines a reusable, self-contained piece of code with distinct functionality. The main benefits of those modules are
Why do I need modules in my stylesheets?
Simply for the same reasons mentioned above. Most stylesheets are a mess, especially because they are shared in a global scope and there is currently no good way to get around this, unless you can use CSSModules in your project. “SCSS modules” are just useful for mixins, functions and variables as they do not generate any CSS code after compilation. The biggest advantages of the module pattern in stylesheets are:
- You do not need to import your stylesheets in a specific order anymore
- You know the exact dependencies of every file
Golden rules of SCSS/SASS modules
To use mixins, functions and variables as modules you need to follow these rules:
- Never import a module in your main file
- Never use more than one mixin / function per module
- Never add code to modules that generates CSS code after compilation
- Never use a function or mixin that was not imported before
So how can I use modules now?
Create a folder named “modules” in your styles directory right next to your main file that imports every other SCSS file.
In that folder create an SCSS partial (e.g. _module.scss) for every reusable piece of code (functions, mixins, variables)
Import those modules in every single file that’s using them at the beginning of that file.
Using modules with a package manager
You could directly import external libraries in your files but I prefer to import them in a module, so there is no need to recognize any other path.
That way you can store settings for those libraries or even rename them in a new mixin.
- If you use SASS partials (_file.scss) there won’t be an error if you forget to import a module that another file has imported before. However you should still import that module on every other file using it, just to make sure that this file can be executed without importing another file before.
- Adding the modules folder to your includePaths or loadPaths option of your SASS compiler is probably not a good idea if your file names collide as importing a file with the same name results in an infinite loop error. So your imports should always looks like @import ‘modules/xxxx’;