Skip to content

Commit

Permalink
Only call .toString() on sass files
Browse files Browse the repository at this point in the history
Calling .toString() is a fairly expensive operation, which allocates
a new string, and copies all of the contents of the file Buffer into
that string. This is fairly fast for small files or small sites, but
quickly starts to take seconds of the total build time on medium
sized sites (in my case, roughly 2 seconds of the overall build was
this call to toString()!)

This change makes it so we only call toString() if we actually want
the result - i.e. if it as a sass file. Thus, we don't call it on
markdown files, image files, video files, etc.
  • Loading branch information
crazy2be committed Jan 2, 2019
1 parent 3e4749b commit d443be9
Showing 1 changed file with 45 additions and 41 deletions.
86 changes: 45 additions & 41 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,17 @@
},

compile = function(config, basePath, files, filename, done) {
if (isPartial(filename)) {
delete files[filename];
done();
return;
}

if (!isAnySassFile(filename)) {
done();
return;
}

var file = files[filename],
filePath = path.join(basePath, filename),
opts = extend({
Expand All @@ -57,54 +68,47 @@
opts.outFile = filePath.replace(/\.s[ca]ss/, '.css');
}

if (isAnySassFile(filename) === true) {
// Append the file's base path to the available include paths.
opts.includePaths.push(fileDir);

// Compile the file using SASS.
sass.render(opts, function (err, result) {
var error = null;

if (err && err instanceof Error) {
error = new Error([
'[metalsmith-sass] Error: ',
err.message, ' -> ',
err.file,
':',
err.line, ':', err.column
].join(''));
} else if (err) {
error = new Error(err);
}
// Append the file's base path to the available include paths.
opts.includePaths.push(fileDir);

// Compile the file using SASS.
sass.render(opts, function (err, result) {
var error = null;

if (err && err instanceof Error) {
error = new Error([
'[metalsmith-sass] Error: ',
err.message, ' -> ',
err.file,
':',
err.line, ':', err.column
].join(''));
} else if (err) {
error = new Error(err);
}

if (error) {
done(error);
return;
}
if (error) {
done(error);
return;
}

// add soure map
if (result.map) {
files[dest+'.map'] = {
contents: result.map,
mode: file.mode
};
}
// add soure map
if (result.map) {
files[dest+'.map'] = {
contents: result.map,
mode: file.mode
};
}

// replace contents
file.contents = result.css;
// replace contents
file.contents = result.css;

// rename file extension
files[dest] = file;
// rename file extension
files[dest] = file;

delete files[filename];
done();
});
} else if (isPartial(filename) === true) {
delete files[filename];
done();
} else {
done();
}
});
},

compileSass = function compileSass(config, files, metalsmith, done) {
Expand Down

0 comments on commit d443be9

Please sign in to comment.