Create simple React component libraries with Webpack

There are a lot of great options and ways you can modularize your js applications these days, and one of my new favorites is bundling related components into their own single entry point using webpack. One of my coworkers has been working on something similar for a few months, so I decided to try it out in some of my own projects.

We’ve been calling these component groupings ‘packages’, or ‘libraries’. It conveniently solves the issue of importing components like so:

import Button from ‘../../../components/button/button’;
import Bio from '../../../components/bio/bio';

To something a bit more manageable:

import { Button, Bio } from 'components';

Kinda way better, right?

In this example, the solution is relatively easy. Let’s say you have this simple webpack/react app:

MyProject
-- public/
---- index.html // -> where webpack puts its bundle
-- src/
---- components/
------ bio/
-------- bio.js
------ button/
-------- button.js
---- pages/
------ about/
-------- about.js
------ home/
-------- home.js
---- index.js // -> core of the react app
-- package.json
-- yarn.lock
-- README.md
-- webpack.config.js

We have a few components in components/, and a couple more in the pages/ directory as well. If we want to share components between them, it’ll result in that ugly relative path.

Instead, we can import each of these components inside a new file called components.js (in the components/ directory), then immediately export them:

import Button from ‘./button/button’;
import Bio from ‘./bio/bio’;
export {
Button,
Bio
}

What does this do? It basically allows us to referenceButton and Bio using only this new file.

We can then add an alias to webpack.config.js that points to it (understanding and writing a complete config file is a bit beyond the scope of this article, so I’ll omit that here):

const path = require(‘path’);module.exports = {
// entry, output, module, and plugin configurations also go here
resolve: {
alias: {
‘components’: path.resolve(__dirname, ‘src/components/components.js’)
}
},
// ...
}

I’ve found this strategy helps you think more logically about components and what buckets they fall into it. In this example, we looked at components and pages, but you could do this easily on a feature level for larger apps if that’s more ideal. E.g., Search, Users, Settings, etc.

You can find a working example of this strategy in action here.

Hope this helps and happy new year!

George is a front-end developer and digital designer living in Oakland, California. He currently codes things as a front-end developer at Scribd. When he’s not in a text editor, he can be found long boarding, playing video games, or napping. Usually napping.

Learning to see. @gwtrev