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 install Sass globally using npm install -g sass which will provide access to the sass executable. You can also add it to your project using npm install --save-dev sass . This provides the executable as well as a library: const sass = require('sass'); const result = sass.
<57. Node-sass is a library that provides binding for Node. js to LibSass, the C version of the popular stylesheet preprocessor, Sass. It allows you to natively compile . scss files to css at incredible speed and automatically via a connect middleware.
You can install Sass by downloading the package from the Official Github Site and add it directly to your path. To install node-sass: Once you install npm, it's time to install node-sass. You can do so by running this command in your terminal to install the package globally.
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:
node_modules/some-module/sass/app
Then in your main scss file you can use:
@import "~some-module/sass/app";
Tilde operator shall resolve any import as a module.
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:
'use strict'; var path = require('path'), gulp = require('gulp'), sass = require('gulp-sass'); var aliases = {}; /** * Will look for .scss|sass files inside the node_modules folder */ function npmModule(url, file, done) { // check if the path was already found and cached if(aliases[url]) { return done({ file:aliases[url] }); } // look for modules installed through npm try { var newPath = path.relative('./css', require.resolve(url)); aliases[url] = newPath; // cache this request return done({ file:newPath }); } catch(e) { // if your module could not be found, just return the original url aliases[url] = url; return done({ file:url }); } } gulp.task("style", function() { return gulp.src('./css/app.scss') .pipe(sass({ importer:npmModule })) .pipe(gulp.dest('./css')); });
Now let's say you installed inuit-normalize
using node. You can simply "require" it on your Sass file:
@import "inuit-normalize";
I hope that helps you and others. Because adding relative paths is always a pain in the ass :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With