Can't render an img with react and webpack - reactjs

Hi guys I'm new to Webpack so I'm having some problems when trying to add the src of an img tag because I'm getting an error, I already tried some solutions that I saw in other similar questions like adding the url-loader but I still can't get it to work
I'm getting this error in my code
ERROR in ./client/src/img/logo.png 1:0
[0] Module parse failed: Unexpected character '�' (1:0)
[0] You may need an appropriate loader to handle this file type, currently no loaders are
configured to process this file. See https://webpack.js.org/concepts#loaders
[0] (Source code omitted for this binary file)
[0] # ./client/src/pages/Homepage.js 108:9-35
[0] # ./client/src/App.js 3:0-40 9:38-46
[0] # ./client/src/index.js 3:0-24 4:50-53
My Webpack.config.js code
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
main: path.join(__dirname, 'client/src/index.js')
},
output: {
path: path.join(__dirname, 'build'),
filename: 'bundle.js'
},
plugins: [new HtmlWebpackPlugin({
title: 'Ig Scraper',
template: path.join(__dirname, 'client/templates/index.ejs'),
filename: 'index.html'
})],
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|express)/,
use: {
loader: 'babel-loader',
options: {
presets: [
"#babel/preset-env",
"#babel/preset-react"
]
},
}
},
{
test: /\.(html)$/,
use: {
loader: 'html-loader',
options: {
attrs: [':data-src']
}
}
},
// {
// test: /\.(png|jpg)$/,
// include: path.join(__dirname, '/client/img'),
// loader: 'file-loader'
// },
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(jpe?g|png|gif|woff|woff2|eot|ttf|svg)(\?[a-z0-9=.]+)?$/,
use: [
{
loader: 'url-loader?limit=100000'
}
]
}
]
},
devServer: {},
resolve: {
extensions: ["*", ".js", ".jsx"]
},
resolveLoader: {
extensions: ["babel-loader"]
},
devtool: 'source-map',
mode: 'development',
resolve: {
fallback: {
fs: false
}
}
};
My Homepage.js code
import React, { useState } from "react";
import axios from "axios";
import '../assets/Homepage.css'
// import logo from '../img/instagramLogo.png'
const Homepage = () => {
return (
<>
<div className="container">
<div className="homepage">
<div className="homepage__igAssets">
<img src={require('../img/logo.png')} alt="" className="ig__logo" />
{/* <img src="./assets/instagram.png" alt="" className="ig__text" /> */}
</div>
<h1 className="homepage__title">¡Let's scrape your instagram account! </h1>
<div className="homepage__elements">
<input className="homepage__input" placeholder="Username..." value= {username} onChange={onChange} />
<button className="homepage__button" onClick={onClick}>Get instagram followers!</button>
</div>
{renderData()}
</div>
</div>
</>
);
};
export default Homepage;
My files organization

Most likely, this error comes from Homepage.js, on the line:
<img src={require('../img/logo.png')} ... />
Require is not meant for images, but for js modules (learn more here).
Erratum: Above is about require in nodejs, it may not be the way to go, but require seems to work fine with webpack.
The way to use images with react would be:
// First, import the image file
import image from './path-to-image.png';
// Later, use it as source in the render
<img src={image} ... />
Your webpack.config.js looks fine (although i'm no expert at such things).
Add: Here is an other question highly related that might help you

Related

Module not found: Error: Can't resolve './component/Hello'

I´m trying to import a simple Component but the webpack seems to cant find it. The route is good and the "resolve" in the webpack config is great too, therefore I cant understand where is the issue.
Give it at look please.
By the way, its a Sails/React environment.
ERROR in ./assets/src/component/Hello.jsx 6:12
Module parse failed: Unexpected token (6:12)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.
Hello.jsx:
import React from 'react'
class Hello extends React.Component {
render() {
return(
<div> // Err supposed to be here (line6)
Hello World!
</div>
)
}
}
export default Hello;
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import Hello from './component/Hello'
const App = () => {
return (
<div>
Simple Sails-React stater
<Hello/>
</div>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
.babelrc:
{
"presets": ["#babel/env", "#babel/react"]
}
webpack config file:
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
entry: './assets/src/index.js'
},
output: {
path: __dirname + '/.tmp/public',
filename: 'bundle.js'
},
module: {
rules: [
{
use: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
},
{
use: ['style-loader', 'css-loader'],
test: /\.css$/
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
plugins: [
new HtmlWebpackPlugin({
template: 'assets/src/index.html'
})
]
};
the structure is like this:
-src
--component
----Hello.jsx
--index.js
--index.html
Could you try change extension to Hello.js or change bable-loader test to
test: /\.(js|jsx)$/,

How to import svg files and use them for src in image

I'm running into an issue that I can't seem to solve.
I have a svg file that I need to include in my project. Since I've build my own boilerplate I want to have the same functionality as CRA in that I can use the svg as the image src.
i.e.
<img src={svgfile} alt="some file" />
What would I need to do to have that functionality?
I tried to use file loader to get it to work but it throws an error.
{
test: /\.(png|jpg|gif|svg)$/,
use: [
{
loader: "file-loader",
options: {}
}
]
},
Any help would be greatly appreciated.
SA
webpack file
{
entry: "./src/browser/index.js",
output: {
path: path.resolve(__dirname, "public"),
filename: "bundle.js",
publicPath: "/"
},
module: {
rules: [
{ test: /\.(js)$/, use: "babel-loader" },
{
test: /\.(png|jpg|gif|svg)$/,
use: [
{
loader: "file-loader",
options: {}
}
]
},
]
},
plugins: [
new webpack.DefinePlugin({
__isBrowser__: "true"
})
]
}
Like
import svgfile from “./path/fileName.svg”;
<img src={svgfile} alt="some file" />
Or
<img src={require(“./path/fileName.svg”} alt="some file" />
Please excuse me for double quotes I am answering in mobile
You can try something like:
test: /\.(?:png|jpg|gif|svg)$/i,
use: [
{
loader: 'file-loader',
options: {
name: 'assets/[hash].[ext]',
}
},
]
Where assets is directory where imported file will be stored after build.

You may need an appropriate loader to handle this file type upload image file

I am using an image file in react-babel-webpack. But it showing an error that
ERROR in ./public/assets/scissors.png
Module parse failed: /home/rohit/Desktop/game/public/assets/scissors.png
Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected character '�' (1:0)
tool.component.js
import React from 'react';
import Paper from '../../public/assets/paper.png';
import Rock from '../../public/assets/rock.png';
class Tools extends React.Component {
render(){
return (
<div>
<img src={Paper} name="Paper" onClick={this.select.bind(this)} className="game-icon" alt="logo" />
<img src={Rock} name="Rock" onClick={this.select.bind(this)} className="game-icon" alt="logo" />
</div>
);
}
};
export default Tools;
webpack.config.dev.js
import path from 'path'
import webpack from 'webpack';
export default {
devtool: 'cheap-module-eval-source-map',
entry: [
'webpack-hot-middleware/client',
path.join(__dirname, '/client/index.js')
],
output: {
path: '/',
publicPath: '/'
},
plugins: [
new webpack.NoErrorsPlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin()
],
module: {
loaders: [
{
test: /\.js$/,
include: path.join(__dirname, 'client'),
loaders: [ 'react-hot', 'babel' ]
},
{ test: /\.css$/, loader: "style-loader!css-loader" },
{ test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [ 'file?hash=sha512&digest=hex&name=[hash].[ext]',
'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
]}
]
},
resolve: {
extentions: [ '', '.js', '.css' ]
}
}
add '.png' into the extensions array:
resolve: {
extensions: [ '', '.js', '.css', '.png' ]
}
edit: resolved typo

Webpack & React. Loaded image can't resolve path 404

At this case I am trying to set up sort of high-order component and further implement 'dynamic' image loads for it. Can you please explain what has been done wrong in order to reference to the inside the component.
React Component
class Slide extends Component {
constructor(props) {
super(props)
}
render () {
let imageLeft = {
backgroundImage: 'url(./assets/introleft.png)'
}
return (
<div className={styles.someStyles}>
<div className={styles.someStyles} style={imageLeft} > </div>
</div>
)
}
}
... state
export default connect(mapStateToProps)(Slide);
Project structure
Webpack config
const path = require('path'),
webpack = require('webpack'),
HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: [
'react-hot-loader/patch',
'webpack-dev-server/client?http://localhost:8080',
'webpack/hot/only-dev-server',
'./index.js'
],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'build'),
publicPath: '/'
},
context: path.resolve(__dirname, 'logic'),
devtool: 'inline-source-map',
devServer: {
hot: true,
contentBase: path.resolve(__dirname, 'build'),
publicPath: '/'
},
module: {
rules: [
{
test: /\.js$/,
use: [
'babel-loader',
],
exclude: /node_modules/
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader?modules',
'postcss-loader',
],
},{
test: /\.png$/,
use: { loader: 'url-loader', options: { limit: 15000 } },
},
{
test: /\.svg$/,
use: {
loader: 'svg-url-loader',
options: {}
}
],
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(),
new HtmlWebpackPlugin({
template: './index.template.html'
})<script> tag
],
};
P.S: Project has no node.js server, just wepback-dev. So react-router uses hash history /#, wounder if it somehow affects the webpack publicPath property.
When you're using backgroundImage: 'url(./assets/introleft.png)', this will be inserted as is (it's just a string), so your url-loader won't be applied to it. Instead you should import the image:
import introleft from './assets/introleft.png';
Webpack will have applied the url-loader and you get back either the data URL or the URL to the extracted image, if the size was too big. All you need to do now is put that URL into your backgroundImage:
backgroundImage: `url(${introleft})`

How to render a foo.md markdown file in react?

I have several .md files (containing long texts) and I want to render them through react. I tried to use markedown-it but the loader returns an error. Here is the webpack.config.js file:
var path = require('path');
var webpack = require('webpack');
var subscript = require('markdown-it');
var superscript = require('markdown-it');
module.exports = {
entry: ['./src/first.jsx'],
devtool: 'cheap-module-eval-source-map',
output: { path: __dirname+"/app", filename: 'bundle.js' },
module: {
loaders: [
{ test: /\.jsx?$/,
loader: 'babel-loader',
query: { presets: ['es2015', 'react'] },
include: path.join(__dirname, 'src')
},
{ test: /\.md/,
loader: 'markdown-it'
}
]
},
'markdown-it': {
preset: 'default',
typographer: true,
use: [subscript, superscript]
}
};
Is there something wrong with that file? How else I can add my *.md files to react?
After reading http://www.shoutinginfrench.com/today-i-made-react-load-markdown/ I tried to use markdown-loader. Following that, I added this to webpack.config file:
{ test: /\.md$/,
loader: "html!markdown"
}
which worked with no problem. Then I tried to add the markdown file to the react component as follow:
import React from 'react';
import { Link } from 'react-router'
import markdownFile from './test-file.md';
export const Test = React.createClass({
rawMarkup(){
return { __html: markdownFile };
},
render() {
return (
<div className="something">
<div className="row">
<div className="col-10">
<div dangerouslySetInnerHtml={this.rawMarkup()} />
</div>
</div>
</div>
);
}
});
But I'm getting the following error:
ERROR in ./src/components/tst.jsx
Module not found: Error: Cannot resolve module 'html' in /Users/..../src/components
# ./src/components/tst.jsx 14:15-39
How can I fix it?!
add { test: /\.md$/, loader: "html!markdown" },{ test: /\.json$/, loader: "json" } to your webpack.config.js .
npm install react-markdown --save-dev

Resources