React does not show Image even complied successfully - Webpack - reactjs

So I would like to use a Image in my React Project, but when I open the browser in order to view my website I am always getting a 404:
import React from "react";
import ReactDOM from "react-dom";
import img from "./App/assets/image.png";
ReactDOM.render(
<img src={img} alt="img"></img>,
document.getElementById("root")
);
this is my webpack.config.js file:
var path = require('path');
module.exports = {
mode: 'development',
entry: './src/index.js',
output:{
path: path.join(__dirname, '/dist/'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.(png|jpg|gif)$/i,
use: [
'file-loader'
// {
// loader: 'file-loader',
// // options:{
// // name: '[name].[ext]',
// // outputPath: 'assets',
// // }
// },
],
},
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
loader: "babel-loader",
options: { presets: ["#babel/env"] }
},
]
},
devServer: {
historyApiFallback: true,
contentBase: path.join(__dirname, "public/"),
port: 3000,
publicPath: "http://localhost:3000/dist/",
hotOnly: true
},
};
the .babelrc file:
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
After that it compiles successfully but the browser-console shows:
GET http://localhost:3000/da8ab57a5dacdcc560a4f73bd6e235a8.png 404 (Not Found)

Related

How to display console.logs using Webpack build?

I'm using Webpack to build a React app. I'm trying to use console.log to debug but they don't show up in the browser console or in the terminal. It doesn't seem to like there's too much on this (The only other question I've found on this is here: Webpack console.log output?)
webpack.config.js
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: './src/App.tsx',
mode: 'development',
module: {
rules: [
{
test: /\.(|ts|tsx|js|jsx)$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-env',
'#babel/preset-react',
'#babel/preset-typescript',
],
plugins: [
'#babel/plugin-proposal-class-properties',
],
},
},
},
{
test: /\.(css|scss)$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(jpe?g|gif|png|svg)$/i,
loader: 'url-loader',
options: {
limit: 25000,
esModule: false,
},
},
],
},
resolve: { extensions: ['.ts', '.tsx', '.js', '.jsx'] },
output: {
path: path.resolve(__dirname, 'dist/'),
publicPath: '/dist/',
filename: 'bundle.js',
},
devServer: {
contentBase: path.join(__dirname, 'public/'),
port: 3000,
publicPath: 'http://localhost:3000/dist/',
hot: true,
},
plugins: [new webpack.HotModuleReplacementPlugin()],
};
App.tsx
import React from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
console.log('test1') // this gets logged
render(<Hello />, document.querySelector('#main'));
Hello.tsx
import React, { RefObject } from 'react';
interface Props { }
interface State { }
console.log('test2') // this gets logged
export default class Hello extends React.Component<Props, State> {
private start() {
console.log('test3') // this doesn't get logged
}
constructor(p: Props) {
super(p);
this.start();
console.log('test4') // this gets logged
}
}
Any insights are appreciated!

Webpack Dev Server (Uncaught SyntaxError: Unexpected token '<' )

Building TS/SASS with Webpack works fine, running this through VSCode Live Server plugin renders the index.html perfectly to the app folder.
Running webpack-dev-server with it looking at the same app folder does not. The page opens but there is a Javascript error Uncaught SyntaxError: Unexpected token '<'
And the page does not render the JS/CSS.
webpack.config.js
// Imports
var path = require("path");
// Plugins
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
// Exports
module.exports = {
mode: 'development',
entry: './src/main.ts',
devtool: "inline-source-map",
resolve: {
extensions: [".ts", ".tsx", ".js"]
},
output: {
filename: 'main.min.js',
path: path.resolve(__dirname, 'app')
},
devServer: {
open: 'http://localhost',
port: 80,
publicPath: path.resolve(__dirname, 'app'),
hot: true
},
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader',
options: { minimize: true }
}
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
},
{
test: /\.scss$/,
use: [
"style-loader",
"css-loader",
"sass-loader"
]
},
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
}),
]
}
tsconfig.json
{
"compilerOptions": {
"sourceMap": true
}
}
main.ts
console.log('Main.ts has loaded')
import './styles/main.scss'
Any help with this would be appreciated, I'm losing my mind lol.
My issue was with syntax in the webpack.config.js file.
I was neglecting to insert a comma at the end of the last entry in every object and array, believing it not to be necessary.
Here is a working config:
// Imports
var path = require("path");
// Plugins
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
// Exports
module.exports = {
mode: 'development',
entry: './src/main.ts',
devtool: "inline-source-map",
output: {
filename: 'main.min.js',
path: path.resolve(__dirname, 'app'),
},
devServer: {
open: 'http://localhost',
port: 80,
},
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
},
{
test: /\.html$/,
use: [
{
loader: 'html-loader',
options: { minimize: true },
}
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader',
]
},
{
test: /\.scss$/,
use: [
"style-loader",
"css-loader",
"sass-loader",
]
},
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html",
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css",
}),
]
}

React app looking for bundle.js in component folder not project root

The errors I get below are shown in the console after I refresh on a nested route (register/email-confirmation). Whereas non-nested routes do not get this error.
I think the main problem is that it's searching for bundle.js and the image in the nested route path, as opposed to the root path.
The errors in my console:
GET http://localhost:3002/register/bundle.js net::ERR_ABORTED
Refused to execute script from 'http://localhost:3002/register/bundle.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
GET http://localhost:3002/register/a5e694be93a1c3d22b85658bdc30008b.png 404 (Not Found)
My webpack.config.js:
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const BUILD_PATH = path.resolve( __dirname, "./client/build" );
const SOURCE_PATH = path.resolve( __dirname, "./client/src" );
const PUBLIC_PATH = "/";
...
module.exports = {
devtool: 'eval-source-map',
context: SOURCE_PATH,
entry: ['babel-polyfill', SOURCE_PATH + '/index.jsx'],
module: {
rules: [
{
test: /\.jsx?$/,
exclude: [/node_modules/, /server/],
use: {
loader: 'babel-loader',
options: {
presets: ['env', 'es2015', 'react', 'stage-1', 'stage-0', 'stage-2'],
plugins: [
'transform-decorators-legacy',
'transform-es2015-destructuring',
'transform-es2015-parameters',
'transform-object-rest-spread'
]
}
}
},
{
test: /\.scss$/,
use: [{
loader: "style-loader"
}, {
loader: "css-loader"
}, {
loader: "sass-loader"
}]
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {}
}
]
},
],
},
output: {
path: BUILD_PATH,
filename: "bundle.js",
},
devServer: {
compress: true,
port: 3002,
historyApiFallback: true,
contentBase: BUILD_PATH,
publicPath: PUBLIC_PATH,
},
plugins: [
new webpack.DefinePlugin(appConstants),
new HtmlWebpackPlugin({
filename: 'index.html',
template: path.resolve(__dirname, 'client/src/index.html'),
inject: true
}),
],
watch: true,
}
I don't know about this bug, but I highly recommend using fuse-box
fuse-box is the future of the build systems, within few minutes you will be running your project with high speed hot reload and many others utitilites...
check this react example seed, it's incredibly amazing..

Webpack throws error about jsx component

I have the following jsx component:
import React, { Component } from 'react';
class App extends Component {
render () {
return (
<div className="app">
<h2>Welcome to React</h2>
</div>
)
}
}
export default App;
and my webpack file:
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
context: path.resolve(__dirname, './src'),
entry: {
app: './index.jsx'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, './dist/assets'),
publicPath: '/assets',
},
devServer: {
contentBase: path.resolve(__dirname, './src')
},
module: {
rules: [
{
test: /\.jsx$/,
exclude: [/node-modules/],
use: [
{
loader: "babel-loader",
options: { presets: ["es2015"] }
}
]
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
use: [{
loader: 'css-loader',
options: { importLoaders: 1 },
}],
}),
},
{
test: /\.(sass|scss)$/,
use: ["style-loader", "css-loader", "sass-loader"]
}
]
},
resolve: {
modules: [
path.resolve(__dirname, './src'),
'node_modules'
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: 'common'
}),
new ExtractTextPlugin({
filename: '[name].bundle.css',
allChunks: true
})
]
}
however when I run:
node_modules/.bin/webpack -d
I get the following error:
Add "babel-preset-react"
npm install babel-preset-react
and add "presets" option to babel-loader in your webpack.config.js
Here is an example webpack.config.js:
module: {
loaders: [{
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['react', 'es2015', 'stage-1']
}
}]
}

Webpack 3: css-loader style-loader error

I am receiving the following error:
ERROR in ./common/app.css Module parse failed:
E:\universal-starter\common\app.css Unexpected token (1:5) You may
need an appropriate loader to handle this file type.
| body {
| background-color: orange;
| }
My App.js file:
import React from 'react';
require('./app.css');
const App = () => <div>Hello from React</div>;
export default App;
My webpack.config:
const webpack = require('webpack');
const path = require('path');
const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin');
const HTMLWebpackPlugin = require('html-webpack-plugin');
module.exports = {
devtool: 'inline-source-map',
entry: [
'react-hot-loader/patch',
'webpack-dev-server/client?http://localhost:3001',
'webpack/hot/only-dev-server',
'./client/index',
],
target: 'web',
module: {
rules: [
{
enforce: 'pre',
exclude: /node_modules/,
loader: 'eslint-loader',
options: {
emitWarning: true
},
test: /\.(js|jsx)$/
},
{
exclude: /node_modules/,
test: /\.js?$/,
use: ['babel-loader']},
// WHY IS THIS WRONG & CAUSING THE PROBLEM?!?!?!?!
// embed styles in styles folder
{
test: /\.css$/,
use: ExtractTextWebpackPlugin.extract({
fallback: 'style-loader',
use: ['css-loader']
})
},
// fonts
{
test: /\.(woff|woff2|eot|ttf|svg)$/,
exclude: /node_modules/,
loader: 'url-loader?limit=1024&name=fonts/[name].[ext]'
},
// examine img file size
{
test: /\.(jpe?g|png|svg|gif)$/,
use: [{
loader: 'url-loader',
options: {
limit: 40000,
name: 'images/[name].[hash].[ext]',
}
},
{
loader: 'image-webpack-loader',
}
]
}
],
},
plugins: [
new ExtractTextWebpackPlugin('./css/styles.css'),
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new HTMLWebpackPlugin({
template: './client/template/index.html',
}),
new webpack.DefinePlugin({
'process.env': { BUILD_TARGET: JSON.stringify('client') },
}),
],
devServer: {
host: 'localhost',
port: 3001,
historyApiFallback: true,
hot: true,
},
output: {
path: path.join(__dirname, '.build'),
publicPath: 'http://localhost:3001/',
filename: 'client.js',
},
};
Very little help out there so far on Webpack 3.
Any ideas?
Thanks!!
Try this:
In your App.js file, replace require('./app.css'); for import './app.css'

Resources