I recently found out about this feature in node-sass named importer, which allows you to handle any encounter with @import
in your sass files.
I want to take advantage of this feature to import .css files from a npm package easily, similarly to Browserify.
Here's my sass file. (index.scss)
@import "normalize.css";
When I run this file through Sass and my importer, it should output this (supposed index.css):
/*! normalize.css v3.0.3 | MIT License | github.com/necolas/normalize.css */
/**
* 1. Set default font family to sans-serif.
* 2. Prevent iOS and IE text size adjust after device orientation change,
* without disabling user zoom.
*/
html {
...
Instead, it outputs this (actual index.css):
@import url(/Users/me/workspace/project/node_modules/normalize.css/normalize.css);
What gives? Why is it that my importer only changes the file path instead of taking the file and combining it with the original file?
Here's my importer and gulp task that runs sass (gulpfile.babel.js):
import gulp from 'gulp';
import sass from 'gulp-sass';
import rename from 'gulp-rename';
import path from 'path';
import fs from 'fs';
let aliases = {};
function importNpmModule(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 {
const basePath = path.resolve('node_modules', url);
const pkgInfo = path.join(basePath, 'package.json');
const info = JSON.parse(fs.readFileSync(pkgInfo));
const newPath = path.join(basePath, info.style);
aliases[url] = newPath; // cache this request
return done({ file: newPath });
} catch(e) {
// If module could not be found, return the original url
aliases[url] = url;
return done({ file:url });
}
}
gulp.task('sassify', () => {
return gulp.src('./index.scss')
.pipe(sass({ importer: inportNpmModule }))
.pipe(rename('index.css'))
.pipe(gulp.dest('public'));
});
EDIT: I also tried using an npm package named sass-module-importer, but it has the exact same problem that I have.