I've been unable to load an image (logo.png) with git-pages since im using webpack, so i tried to see i could just see it on my local. Seems like it doesnt work either. I did use import, and downloaded the dependencies.
The structure of my project to visualize where could be the issue :
- dist (folder)
- index.html
- main.js (bundled from index.js generated with webpack)
- src (folder)
- images (folder) > logo.png
- scripts (folder) > header.js
- index.js
Here is my webpack.config.js
const path = require('path');
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
},
devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(png|svg|jpg|jpeg|gif)$/i,
type: 'asset/resource',
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: 'asset/resource',
},
{
test: /\.(png|jpeg|gif)$/i,
use: [
{
loader: 'file-loader',
}
],
},
{
test: /\.(png|jpeg|gif)$/i,
use: [
{
loader:'url-loader',
options:{
limit:8192,
}
}
]
}
],
},
};
My package.json file :
{
"name": "test-stackover",
"version": "1.0.0",
"description": "",
"main": "webpack.config.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "webpack --watch",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"css-loader": "^6.7.1",
"file-loader": "^6.2.0",
"style-loader": "^3.3.1",
"url-loader": "^4.1.1",
"webpack-cli": "^4.10.0"
}
}
My header.js file (inside de src folder) :
import iconLogo from '/src/images/logo.png';
const createElement = (type, attributes, ...children) => {
const element = document.createElement(type);
for (let key in attributes) {
element.setAttribute(key, attributes[key])
}
children.forEach(child => {
if(typeof child === 'string'){
element.appendChild(document.createTextNode(child));
}else{
element.appendChild(child);
}
});
return element;
}
const createHeader = () =>{
// logo
const imgLogo = createElement('img', {src: iconLogo, alt:'logo'},'');
/* const imgLogo = createElement('img', {src: {iconLogo}, alt:'logo'},''); didnt work */
const aLogo = createElement('a',{href : '#', class : 'logo'}, imgLogo);
document.body.appendChild(aLogo);
}
export{ createHeader };
My index.js file :
import { createHeader } from './script/header.js';
createHeader();
and finally the HTML file, the script is from my bundle :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test</title>
<script src="main.js" defer></script>
</head>
<body>
</body>
</html>
I hope i gave enough detailled infos about the issues ?