You’ve probably used Webpack
to bundle JavaScript, but what about images, fonts, and other static assets? In this article, we’ll explore how Webpack can manage those assets in a practical — and surprisingly elegant — way.
Why does this matter?
Imagine you're building an app full of images, icons, custom fonts, and PDFs. Without an organized strategy, your project can become messy. Webpack lets you import assets directly into your code, and it takes care of everything: renaming, compressing, placing files correctly, and more.
Prerequisites
- Node.js installed
- Webpack and Webpack CLI
- Basic JavaScript knowledge
npm install --save-dev webpack webpack-cli
1. Importing images directly in JavaScript
Webpack lets you import images like JS modules:
import logo from './images/logo.png';
const img = document.createElement('img');
img.src = logo;
document.body.appendChild(img);
Webpack copies the image to the build folder and updates the path automatically.
2. Asset Modules
Since Webpack 5, there's no need for file-loader
or url-loader
. Use asset/resource
, asset/inline
, and asset
:
{
test: /\.(png|jpg|gif)$/i,
type: 'asset/resource',
}
3. Fonts and SVGs
You can import fonts like this:
import './fonts/roboto.woff2';
And inline SVGs:
{
test: /\.svg$/,
type: 'asset/inline',
}
4. PDFs and large files
For files meant to be downloaded rather than displayed:
{
test: /\.pdf$/,
type: 'asset/resource'
}
5. Hashed filenames
For better cache management:
output: {
filename: '[name].[contenthash].js',
assetModuleFilename: 'assets/[hash][ext][query]'
}
Final thoughts
Webpack is more than a JS bundler. Using asset management wisely can make your project more organized, efficient, and professional. Start small — maybe with your logo — and gradually unlock the full power of this amazing tool.
Found this useful? Hit the ❤️ or leave a comment!
Top comments (0)