Improve SEO with a Simple Tweak to Your Webpack File-Loader Config

Webpack

You're building a website -- more than a website... a modern web app -- and you're not shy about using JavaScript. But all that JavaScript sent you directly to Webpack.

The problem with Webpack and the file-loader (well, one of the problems) is that they will happily mangle all your filenames by default. Don't let this happen. You're losing valuable SEO juice.

Pop Quiz

Which looks better to Google when it crawls your site?

A) 956e522a233d6cdf53aeaea3fb892541.png
B) brief-description-of-the-image-contents.png

Yeah, B. But before we implement B, it's important to understand the merit in A.

While choice A is absolutely useless in terms of SEO, it's great for cache busting. By that I mean that the seemingly random string of numbers and letters is actually a hash of the content. File-loader assigns a new filename to your content only when the content changes. On subsequent page requests the client receives the new content instead of the cached (old) content (Webpack automagically adjusted the filename reference in the JSX / HTML for you).

webpack.config.js

{  // ...  module: {    // ...    loaders: [      {        test: /\.(ico|png|gif|jpg|svg)$/,        loader: 'file?name=[name].[ext]?[hash:5]'      },      // ...    ],  },}

We simply tell the file-loader, abbreviated here as "file", to use a name of [name].[ext] and append a hash of the content.

We could have simply used [hash] but I prefer [hash:5] because it produces a smaller value (only five characters long). Which gives us:

brief-description-of-the-image-contents.png?956e5

instead of

brief-description-of-the-image-contents.png?956e522a233d6cdf53aeaea3fb892541

Voila! We have descriptive file names and the ability to bust the cache when the content changes.

Further Reading


P.S. There's nothing wrong with Gulp. It's actually great in combination with Webpack. But that's a story for another day.

Level up Your React + Redux + TypeScript

for free with articles, tutorials, sample code, and Q&A.