Currently in our Sass files we have something like the following:
@import "../../node_modules/some-module/sass/app";
This is bad, because we're not actually sure of the path: it could be ../node_modules
, it could be ../../../../../node_modules
, because of how npm installs stuff.
Is there a way in Sass that we can search up until we find node_modules? Or even a proper way of including Sass through npm?
You can use a Sass
importer
function to do so. Cf. https://github.com/sass/node-sass#importer--v200.The following example illustrates node-sass@3.0.0 with node@0.12.2:
Install the bower dependency:
The Sass file:
The node renderer file:
This one is simple and not recursive. The
require.resolve
function could help to deal with the tree – or wait until npm@3.0.0 to benefit from the flat dependency tree.I made the sass-npm module specifically for this.
In your SASS:
I normally use gulp-sass (which has the same 'importer' option as regular SASS)
Then, in your
.pipe(sass())
, add the importer as an option:As Oncle Tom mentioned, the new version of Sass has this new
importer
option, where every "import" you do on your Sass file will go first through this method. That means that you can then modify the actual url of this method.I've used
require.resolve
to locate the actual module entry file.Have a look at my gulp task and see if it helps you:
Now let's say you installed
inuit-normalize
using node. You can simply "require" it on your Sass file:I hope that helps you and others. Because adding relative paths is always a pain in the ass :)
You can add another includePaths to your render options.
Plain example
Snippet based on example from Oncle Tom.
That should do. You can include the files from package using
@import "my-cool-package/super-grid
Webpack and scss-loader example
Notice the last argument, includePaths has to be array. Keep in mind to use right format
If you are looking for a handy answer in 2017 and are using Webpack, this was the easiest I found.
Suppose your module path is like:
Then in your main scss file you can use:
Tilde operator shall resolve any import as a module.