Created
September 2, 2018 13:53
-
-
Save madeinfree/f991e9f4b08bf15da51437c6078fcf91 to your computer and use it in GitHub Desktop.
Commonjs Semantic UI React Tree Shaking babel plugin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = function(babel) { | |
const { types: t } = babel; | |
const SingleTemplate = `semantic-ui-react/dist/commonjs/{{type}}/{{moduleName}}`; | |
const findTypeFolderToName = name => { | |
switch (name) { | |
case 'Grid': | |
case 'Breadcrumb': | |
case 'Form': | |
case 'Menu': | |
case 'Message': | |
case 'Table': | |
return 'collections'; | |
case 'Button': | |
case 'Container': | |
case 'Divider': | |
case 'Flag': | |
case 'Header': | |
case 'Icon': | |
case 'Image': | |
case 'Input': | |
case 'Label': | |
case 'List': | |
case 'Loader': | |
case 'Rail': | |
case 'Reveal': | |
case 'Segment': | |
case 'Step': | |
return 'elements'; | |
case 'Accordion': | |
case 'Checkbox': | |
case 'Dimmer': | |
case 'Dropdown': | |
case 'Embed': | |
case 'Modal': | |
case 'Popup': | |
case 'Progress': | |
case 'Rating': | |
case 'Search': | |
case 'Sidebar': | |
case 'Sticky': | |
case 'Tab': | |
case 'Transition': | |
return 'modules'; | |
case 'Confirm': | |
case 'MountNode': | |
case 'Pagination': | |
case 'Portal': | |
case 'Radio': | |
case 'Ref': | |
case 'Responsive': | |
case 'Select': | |
case 'TextArea': | |
case 'TransitionablePortal': | |
return 'addons'; | |
case 'Advertisement': | |
case 'Card': | |
case 'Comment': | |
case 'Feed': | |
case 'item': | |
case 'Statistic': | |
return 'views'; | |
default: | |
throw new Error(`Can't find any type folder for ${name}, please check it the correct.`); | |
} | |
}; | |
return { | |
name: 'semantic-ui-react-tree-shake', // not required | |
visitor: { | |
ImportDeclaration(path) { | |
const { node } = path; | |
const isSemanticUIReact = node.source.value === 'semantic-ui-react'; | |
if (isSemanticUIReact) { | |
const totalImport = node.specifiers.map(specifier => specifier.imported.name); | |
const replaceImport = totalImport.map(name => | |
t.importDeclaration( | |
[t.importDefaultSpecifier(t.identifier(name))], | |
t.stringLiteral( | |
SingleTemplate.replace(/{{moduleName}}/, name).replace( | |
/{{type}}/, | |
findTypeFolderToName(name) | |
) | |
) | |
) | |
); | |
path.insertAfter(replaceImport); | |
path.remove(); | |
} | |
} | |
} | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment