Skip to content

Instantly share code, notes, and snippets.

@jpnelson
Last active April 9, 2017 23:33
Show Gist options
  • Save jpnelson/efd41b51d650a47e190f20b1c29d2e92 to your computer and use it in GitHub Desktop.
Save jpnelson/efd41b51d650a47e190f20b1c29d2e92 to your computer and use it in GitHub Desktop.
Styled components – add a displayName
const path = require('path');
function basename(str) {
var base = new String(str).substring(str.lastIndexOf('/') + 1);
if(base.lastIndexOf(".") != -1)
base = base.substring(0, base.lastIndexOf("."));
return base;
}
module.exports = function (fileInfo, api) {
const fileName = basename(fileInfo.path).split('.')[0];
const { jscodeshift } = api;
const variableDeclaredStyledComponent = jscodeshift(fileInfo.source)
.find(jscodeshift.ExportDefaultDeclaration)
.replaceWith((nodePath) => {
const { node } = nodePath;
return jscodeshift.variableDeclaration('const', [
jscodeshift.variableDeclarator(jscodeshift.identifier(fileName), node.declaration)
]);
})
.toSource();
return `${variableDeclaredStyledComponent}
${fileName}.displayName = '${fileName}';
export default ${fileName};
`;
};

This will transform code like this:

Component.jsx:

import styled from 'styled-components';

export default styled.div`
  margin-top: 10px;
`;

Into:

import styled from 'styled-components';

const Component = styled.div`
  margin-top: 10px;
`;

Component.displayName = 'Component';
export default Component;

Where Component is the name of the file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment