Webpack Handling Assets
Learn how to handle images, fonts, and other assets with Webpack. Specifically, we will go over the asset/resource, asset/inline, and asset/source types.
Table of Contents 📖
- Webpack and Assets
- Webpack asset/resource
- Webpack asset/inline
- Webpack asset/source
- Webpack Asset Customization
Webpack and Assets
Webpack allows us to bundle up assets such as images, icons, fonts, etc. Even better, Webpack has built in asset modules that allow us to handle assets. In other words, we no longer need to install and configure additional loaders.
Webpack asset/resource
To demonstrate, lets handle JPG images with Webpack.
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
})
],
module: {
rules: [
{
test: /\.jpg$/,
type: 'asset/resource'
}
]
},
};
Setting the type key to asset/resource tells Webpack to emit a seprate file and export the URL. This is better demonstrated with an example.
import CodeJPG from '../images/code.jpg';
console.log(CodeJPG); // http://127.0.0.1:5500/dist/109790ee0c4f3b168dbf.jpg
When Webpack bundles this JavaScript file, it adds the JPG to the bundle with a randomly generated name. If we look at the bundle, this is the structure.
[object Object]
Webpack asset/inline
Webpack allows us to export the asset in different ways. For example, instead of exporting a URL, we can export a data URI by setting the type to asset/inline.
module: {
rules: [
{
test: /\.jpg$/,
type: 'asset/inline'
}
]
},
import CodeJPG from '../images/code.jpg';
console.log(CodeJPG); // data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAM
Webpack asset/source
We can also export the asset as its raw code by setting the type to asset/source.
module: {
rules: [
{
test: /\.jpg$/,
type: 'asset/resource'
},
{
test: /\.txt$/,
type: 'asset/source'
}
]
},
Lets demonstrate this with a text file. Consider the following text file.
Download WittCepter! The best chrome extension!
Now we just need to import it and log out the contents.
import WittCepterText from '../assets/wittcepter.txt';
console.log(WittCepterText); // Download WittCepter! The best chrome extension!
Webpack Asset Customization
Webpack allows us to customize things like the name of the asset. By default Webpack emits assets by using the substitution [hash][ext][query] when type is set to asset/resource. We can change this by setting the assetModuleFilename key in the Webpack output object.
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
assetModuleFilename: 'images/[name][ext]'
},
Here, the output will create an images directory and fill it with the name of the asset followed by the extension.
[object Object]