NextJS, Performance

When Webpack Takes Too Long to Process Images

Sorting out images in Webpack is not too bad up to a point. The url-loader + file-loader combination is usually enough to satisfy needs. However, when you have too many require() for large images, it can take up to 20s or longer to hot-reload after a compile…

Here’s how to mitigate the situation.

We’re using NextJS here, therefore the rules.push, but if you’re not on NextJS, you can just add this to your Webpack rules. Instead of relying only upon file-loader or url-loader, add a cache-loader in front of it, with the readOnly option set to true.

Do an npm install for all the loaders that we need, then:

config.module.rules.push({
    test: /\.(jpg|png)$/i,
    use: [
        {
            loader: 'cache-loader',
            options: {
                readOnly: true
            }
        },
        {
            loader: 'url-loader',
            options: {
                limit: 8192,
                name: '[name]_[hash].[ext]',

                // The following two configs are for NextJS:
                publicPath: '/_next/static/images',
                outputPath: 'static/images/'
            }
        }
    ]
})

By setting readOnly to true, we will only be sorting through all the messy and gigantic requiring of images once and for all, when Webpack starts for the first time.

However, this would also mean that whatever changes are made to the images, we will have to restart the server to have it reflected. To us, it’s a worthy compromise, but your mileage might differ. Use it wisely.

Standard

One thought on “When Webpack Takes Too Long to Process Images

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.