As you migrate from legacy, vanilla code systems towards advanced build systems and single-page applications, you may notice some changes that don’t make immediate sense. There are additional steps that are a bit unintuitive, and it’s not clear what problem is being solved. One such difference is that <img src="./file.gif" /> no longer works. You now have to use import image from './file.gif';. Why?

With a build system like Webpack, your application is no longer running in the same directory as your HTML, e.g. your src directory. It goes through a “build” process that first optimizes the files before outputting the final result into a different directory. Webpack typically starts with your index.js or index.ts file. It concatenates and minifies every JavaScript file it finds to create a single, gigantic, optimized JavaScript file that contains all of your code. That single JS file is inserted into your index.html, and that index.html file is what you see in your browser. This finalized application runs from your build directory in a production build or from memory in a development build, not from your src directory. For a React application, your build directory, aside from the CSS and JavaScript files that Webpack generates, will look about the same as your public directory.

If Webpack never sees your image file, it won’t put it into the build directory. For all it knows, it’s just an unused file, so it shouldn’t be put into the final output. Similarly, if you create a my-file.js in your src directory but you never use it anywhere, Webpack won’t include it in the final bundle. This is a good thing! It would be a waste of space!

#webpack #web-development #programming #software-development #react

Why must images be imported for Webpack?
7.45 GEEK