Today I Learned

6 posts by kamilkorczyński

Styled-components pleasant class names

Styled-components generate unique hashes for each styled-component you create. They look like .nNUbag or .JbCpiZ. From a production perspective, these names are beneficial, since it reduces bundle size, but the development process is a nightmare.

Thankfully, there is a solution: babel-plugin-styled-components. It changes the class names to use the component name, which will help you in debugging process. The exact pattern is fileName__componentName-hash, eg. styles__StyledSearchBar-hXxaWb. Also, you don’t have to worry about production bundle size, cause it works only in development.

If you use create-react-app, the plugin is already set up. The only thing you have to do is update your imports.

import styled from 'styled-components/macro';

How to exclude code from production in build time

Sometimes you may want to add some code which will be available only in development, but you don’t want to mess your bundle with a dead code. You can do this with webpack version 4. Setting mode to production in your webpack config will remove any code that is not designed for selected environment.

if (process.env.NODE_ENV === 'development') {
  console.warn('This block will be removed during building you bundle')
}

Reducing main bundle size with React lazy

On one of our projects we were able to reduce main bundle size from ~1080kB to ~820kB only by lazy loading one library (recharts).

in router file

import React, {Component, lazy, Suspense} from 'react'
//other imports

const StatisticsComponent = lazy(() => import('./path/to/component'))

export class Root extends Component {
  
  render(){
    return(
      <Router history={history}> 
        <Switch>
          // other routes
          <Suspense fallback={<div>Loading...</div>}>
            <Route exact component={StatisticsComponent} path='/statistics' />
          </Suspense>
        </Switch>
      </Router > 
      )
  }
}