Reputation: 35
I am trying to bundle an application using webpack and I'm using html-loader with file-loader to bundle images into an 'imgs' folder within the dist directory (which is not happening).
I have tried importing an image into one of the javascript entry points and this works fine, file-loader recognized the image and bundles it correctly.
File system:
Build script and dependencies from package.json:
"build": "webpack --config webpack.prod.js"
"dependencies": {},
"devDependencies": {
"css-loader": "^3.2.0",
"file-loader": "^4.2.0",
"glob": "^7.1.5",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"style-loader": "^1.0.0",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.9",
"webpack-dev-server": "^3.9.0",
"webpack-merge": "^4.2.2"
}
webpack.prod.js:
const path = require("path");
const common = require("./webpack.common");
const merge = require("webpack-merge");
module.exports = merge(common, {
mode: "production",
output: {
filename: "main.[contentHash].js",
path: path.resolve(__dirname, "dist")
},
});
webpack.common.js:
const HtmlWebpackPlugin = require("html-webpack-plugin");
const glob = require("glob");
module.exports = {
entry: glob.sync("./src/scripts/*.js"),
plugins: [
new HtmlWebpackPlugin({
template: "./src/template.html"
})
],
module: {
rules: [
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
},
{
test: /\.html$/,
use: {
loader: "html-loader",
options: {
attrs: [":data-src"]
}
}
},
{
test: /\.(svg|png|jpg|gif)$/,
use: {
loader: "file-loader",
options: {
name: "[name].[hash].[ext]",
outputPath: "imgs/"
}
}
}
]
}
}
from template.html:
<div class="home-screen">
<div class="app-container">
<div>
<img width="54" height="54" data-name="calculator" src="/src/assets/calc-icon.png"></img>
<p>Calculator</p>
</div>
<div>
<img width="54" height="54" data-name="video-player" src="/src/assets/video-player-icon.png"></img>
<p>Video Player</p>
</div>
<div>
<img width="54" height="54" data-name="temp-converter"
src="/src/assets/temp-converter-icon.png"></img>
<p>Temperature Converter</p>
</div>
<div>
<img width="54" height="54" data-name="color-game" src="/src/assets/color-game-icon.png"></img>
<p>Color Game</p>
</div>
<div>
<img id="camera-icon" width="54" height="54" data-name="camera-app"
src="/src/assets/camera-icon.png"></img>
<p>Camera</p>
</div>
So when I run npm run build
I expect the dist directory to include a index.html, main.js and an imgs
folder containing my images but the imgs
folder simply doesn't show up with no error messages to indicate why. Any help would be much appreciated.
Upvotes: 0
Views: 909
Reputation: 26
You are referencing "/src/assets/" for your images from the template.html file that is already inside your src folder. So when comparing with your base directory it is looking for /src/src/assets/ which doesn't exist.
Change the img src attributes inside src/template.html to use "./assets" instead of "/src/assets" to solve the problem.
Upvotes: 1