Importing anything as React/Preact components with webpack
In this short story, I’ll demonstrate how to import assets (images, videos, etc.) as React/Preact components and make your code clean and neat.
In my previous story, I was importing CSS as components. After using decss for a while, I’ve realized that the underlying concept is applicable not only to CSS but any assets!
This idea inspired me, so I’ve built defile. It might look like magic, but in fact, the implementation is trivial. It simply wraps the output of file-loader into a component constructor. Despite the simplicity, it allows making the code more expressive and neat.
By default, defile-loader generates a link component with predefined href
prop:
defile allows to redefine the tag and the prop name so that you can import images as img
components (loader: 'defile/react?tag=img&prop=src!file'
):
It also allows to redefine the default props so that you can set the meaningful defaults (loader: 'defile/react?{tag: "kind", prop: "src", defaultProps: {kind: "subtitles"}}!file'
):
If you want to give it a try, see defile docs.
If you like it, star the repo and share the post and also follow me on Twitter.
Thank you for reading!