This will be a guide on how you can use optimized version of react highlight

Why there is a need of optimisation ?

The code

require('highlight.js/lib/languages/' + lang));

uses every file in the languages directory, so webpack includes every file as module in your bundle. It doesn't know which language you are using, it makes the bundle size big and if you are obsessed with web performance and optimisations, then you certainly don't like it.

How to optimise ?

There are plugins which are useful to give webpack more information about which module should be included in the bundle.  ContextReplacementPlugin - It allows to override the inferred information i.e provide a new regular expression (You get to choose languages you want to include).
For the react-highlight, we configured our webpack

var webpack = require('webpack')
    module.exports = {
     // ...
     plugins: [
        new webpack.ContextReplacementPlugin(
            /highlight.js/lib/languages$/,
             new RegExp(`^./(javascript)$`)
              )
        ]
    }

we only included javascript but you can pass as many languages as you need in RegExp.

We are done with our webpack configuration, now we want to use it as a component, so we have to pass langauges as a array prop specifying the language we want to use

import Highlight from 'react-highlight'

<Highlight languages={['javascript']}>Hello React</Highlight>

Usage with Gatsby

In Gatsby, you have to modify the existing webpack configuration in your gatsby-node.js

Here is the example to use with Gatsby

exports.modifyWebpackConfig = ({ config, stage }) => {
  config.plugin(
    'Modify',
    () =>
      new webpack.ContextReplacementPlugin(
        /highlight.js/lib/languages$/,
        new RegExp(`^./(javascript)$`)
      )
  )
  return config
}

import Highlight from 'react-highlight'

<Highlight languages={["javascript"]}>Hello React</Highlight>
© Neostack