@helpscout/hsds-react
Version:
React component library for Help Scout's Design System
90 lines (72 loc) • 2.53 kB
JavaScript
var _require = require('fs'),
readdirSync = _require.readdirSync,
statSync = _require.statSync;
var _require2 = require('path'),
join = _require2.join,
resolve = _require2.resolve;
var dirs = function dirs(p) {
return readdirSync(p).filter(function (f) {
return statSync(join(p, f)).isDirectory();
});
};
var COMPONENT_NAMES = [];
try {
COMPONENT_NAMES = dirs(resolve(__dirname, '../../components'));
} catch (e) {
throw new Error('Components dir not found');
}
module.exports = function (babel) {
var t = babel.types;
return {
name: 'hsds-component-import',
visitor: {
ImportDeclaration: function ImportDeclaration(path, state) {
var packages = state.opts.packages ? [].concat(state.opts.packages) : ['@helpscout/hsds-react'];
var packageName = path.node.source.value;
if (isWrongPackage(packageName, packages)) return null;
if (!areAllValidComponents(path.node.specifiers)) return null;
if (packageName.endsWith('/')) {
packageName = packageName.slice(0, packageName.length - 1);
}
if (!packageName.includes('components')) {
packageName += '/components';
}
var program = path.findParent(t.isProgram);
path.node.specifiers.forEach(function (specifier) {
var identifier = specifier.local;
var identifierName = identifier.name;
var defaultImportSpecifier = t.importDefaultSpecifier(identifier);
var pkgPath = "" + packageName;
if (!packageName.includes(identifierName)) {
pkgPath += "/" + identifierName;
}
var newImportDeclaration = t.importDeclaration([defaultImportSpecifier], t.stringLiteral(pkgPath));
program.node.body.unshift(newImportDeclaration);
});
path.remove();
}
}
};
};
function areAllValidComponents(specifiers) {
if (!specifiers.length) return false;
if (!COMPONENT_NAMES.length) return false; // If Button is not present something odd happened, bail
if (!COMPONENT_NAMES.includes('Button')) return false;
for (var i = 0; i < specifiers.length; i++) {
if (!COMPONENT_NAMES.includes(specifiers[i].local.name)) {
return false;
}
}
return true;
}
function isWrongPackage(packageName, packages) {
if (!packageName) return true;
var found = false;
for (var i = 0; i < packages.length; i++) {
if (packageName.includes(packages[i])) {
found = true;
}
}
return !found;
}
;