babel-plugin-base-path
Version:
Add first-class support for transforming relative asset paths to absolute one's.
79 lines (62 loc) • 3.02 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.replaceMatchesInString = exports.isStyledComponent = exports.importLocalName = undefined;
exports.getOption = getOption;
var _babelTypes = require('babel-types');
var t = _interopRequireWildcard(_babelTypes);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function getOption({ opts }, name, defaultValue = true) {
return opts[name] === undefined || opts[name] === null ? defaultValue : opts[name];
}
const importLocalName = exports.importLocalName = (name, state) => {
let localName = name === 'default' ? 'styled' : name;
state.file.path.traverse({
ImportDeclaration: {
exit(path) {
const { node } = path;
if (node.source.value === 'styled-components') {
for (const specifier of path.get('specifiers')) {
if (specifier.isImportDefaultSpecifier()) {
localName = specifier.node.local.name;
}
if (specifier.isImportSpecifier() && specifier.node.imported.name === name) {
localName = specifier.node.local.name;
}
if (specifier.isImportNamespaceSpecifier()) {
localName = specifier.node.local.name;
}
}
}
}
}
});
return localName;
};
const isStyledComponent = exports.isStyledComponent = (tag, state) => {
if (t.isCallExpression(tag) && t.isMemberExpression(tag.callee) && tag.callee.property.name !== 'default' /** ignore default for #93 below */) {
// styled.something()
return isStyledComponent(tag.callee.object, state);
} else {
return t.isMemberExpression(tag) && tag.object.name === importLocalName('default', state) || t.isCallExpression(tag) && tag.callee.name === importLocalName('default', state) ||
/**
* #93 Support require()
* styled-components might be imported using a require()
* call and assigned to a variable of any name.
* - styled.default.div``
* - styled.default.something()
*/
state.styledRequired && t.isMemberExpression(tag) && t.isMemberExpression(tag.object) && tag.object.property.name === 'default' && tag.object.object.name === state.styledRequired || state.styledRequired && t.isCallExpression(tag) && t.isMemberExpression(tag.callee) && tag.callee.property.name === 'default' && tag.callee.object.name === state.styledRequired;
}
};
const replaceMatchesInString = exports.replaceMatchesInString = (string, matches, cb) => {
let transformedString = string;
for (let i = 0; i < matches.length; ++i) {
const match = matches[i];
const replacement = cb(match);
// Note: Swap in the prefixed URL
transformedString = transformedString.replace(match, replacement);
}
return transformedString;
};