Skip to content

Commit

Permalink
apply V8 fast property hack only if needed
Browse files Browse the repository at this point in the history
This plugin uses V8 fast property hack https://stackoverflow.com/questions/24987896/, but it's not needed if no properties are deleted.
  • Loading branch information
shinnn committed Nov 1, 2017
1 parent 577fb9e commit bf3c458
Showing 1 changed file with 20 additions and 12 deletions.
32 changes: 20 additions & 12 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
/*!
* metalsmith-babel | MIT (c) Shinnosuke Watanabe
* https://github.com/babel/metalsmith-babel
*/
'use strict';

const path = require('path');
const pathLib = require('path');

const dirname = pathLib.dirname;
const extname = pathLib.extname;
const join = pathLib.join;
const relative = pathLib.relative;

const babel = require('babel-core');
const SafeBuffer = require('safe-buffer').Buffer;
const toFastProperties = require('to-fast-properties');

module.exports = function metalsmithBabel(options) {
options = Object.assign({}, options);
let noFilesRenamed = true;

return function metalsmithBabelPlugin(files, metalsmith) {
Object.keys(files).forEach(originalFilename => {
const ext = path.extname(originalFilename).toLowerCase();
for (const originalFilename of Object.keys(files)) {
const ext = extname(originalFilename).toLowerCase();
if (ext !== '.js' && ext !== '.jsx') {
return;
}
Expand All @@ -25,11 +27,11 @@ module.exports = function metalsmithBabel(options) {
if (originalFilename !== filename) {
files[filename] = files[originalFilename];
delete files[originalFilename];
toFastProperties(files);
noFilesRenamed = false;
}

const result = babel.transform(String(files[filename].contents), Object.assign({}, options, {
filename: path.join(metalsmith.directory(), metalsmith.source(), originalFilename),
filename: join(metalsmith.directory(), metalsmith.source(), originalFilename),
filenameRelative: originalFilename,
sourceMapTarget: filename
}));
Expand All @@ -40,15 +42,21 @@ module.exports = function metalsmithBabel(options) {
contents: SafeBuffer.from(JSON.stringify(result.map))
};

// https://github.com/babel/babel/blob/v6.14.0/packages/babel-core/src/transformation/file/options/config.js#L123
// https://github.com/babel/babel/blob/v6.23.0/packages/babel-core/src/transformation/file/options/config.js#L123
if (options.sourceMap !== 'both' && options.sourceMaps !== 'both') {
result.code += `\n//# sourceMappingURL=${
path.relative(path.dirname(filename), sourcemapPath).replace(/\\/g, '/')
relative(dirname(filename), sourcemapPath).replace(/\\/g, '/')
}\n`;
}
}

files[filename].contents = SafeBuffer.from(result.code);
});
}

if (noFilesRenamed) {
return;
}

toFastProperties(files);
};
};

0 comments on commit bf3c458

Please sign in to comment.