@deron
To serve images using webpack, you can follow these steps:
1
|
npm install --save-dev file-loader |
file-loader
is a webpack loader that allows you to handle various types of assets, including images.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
module.exports = { // ... module: { rules: [ // ... { test: /.(png|svg|jpg|jpeg|gif)$/i, use: [ { loader: 'file-loader', options: { name: 'images/[name].[hash].[ext]', }, }, ], }, ], }, }; |
This configuration tells webpack to use the file-loader
for any image file (with extensions .png, .svg, .jpg, .jpeg, .gif).
1 2 3 4 5 |
import myImage from './path/to/image.png'; const imgElement = document.createElement('img'); imgElement.src = myImage; document.body.appendChild(imgElement); |
In this example, myImage
holds the path to the image file, which is resolved by webpack and bundled along with the rest of the code.
1 2 3 4 5 |
// For development npx webpack serve // For production npx webpack |
The images will be handled by webpack based on the configured setup, and you can access them in the browser through the served bundles.