Images do not display with Webpack 2 - javascript

My tree view:
- app
- App.js
- assets
- Linux.png
- render-web.js
- webpack.config.js
My config:
const path = require('path');
const webpack = require('webpack');
module.exports = {
devtool: 'eval',
entry: [
'react-hot-loader/patch',
'webpack-dev-server/client?https://localhost:9000',
'webpack/hot/only-dev-server',
'./render-web'
],
output: {
path: path.join(__dirname, 'assets'),
filename: 'bundle.js',
publicPath: '/assets/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
],
devServer: {
compress: true,
https: true,
historyApiFallback: true,
inline: false,
port: 9000,
hot: true,
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
ast: false,
babelrc: false,
comments: false,
minified: true,
presets: ['es2015', 'react', 'stage-0'],
plugins: ['syntax-flow', 'react-hot-loader/babel'],
}
},
{
test: /node_modules\/react-native/,
loader: 'ignore-loader',
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'url-loader?limit=9999999',
]
},
],
},
};
My entry file:
/* globals document */
import {AppContainer} from 'react-hot-loader';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './app/App';
const rootElement = document.getElementById('reactors');
ReactDOM.render(
<AppContainer>
<App />
</AppContainer>,
rootElement
);
if (module.hot) {
module.hot.accept('./app/App', () => {
const NextApp = require('./app/App').default;
ReactDOM.render(
<AppContainer>
<NextApp />
</AppContainer>,
rootElement
);
});
}
Then from app/App.js:
import LinuxIcon from '../assets/Linux.png';
<img src={LinuxIcon} />
The path is correct (if I change it, webpack complains it does not exist).
It generates a base64 image:
data:image/png;base64,77+...too long to paste
But it just displays a blank square (no image). What am I doing wrong? Thanks!
BTW using:
file-loader#0.10.0
url-loader#0.5.7
webpack#2.2.1
webpack-dev-server#2.3.0
PS I've tried to move the assets directory into App as I've seen suggested but with no luck.

Related

React doesn't render

I am begining with React using Webpack to make the configuration. I made all step by step. No error message on console or browser but the h1 that I want to insert doesn't appear.
I know that React is v.18 but I am using React v.17
App.jsx
import React from 'react'
const App = () => {
return (
<h1>Holaaa</h1>
);
}
export default App;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/app.jsx';
ReactDOM.render (<App/>, document.getElementById ("Hello"))
webpack.config.js
const path = require ("path");
const HtmlWebpackPlugin = require ('html-webpack-plugin')
const MiniCssExtractPlugin = require ('mini-css-extract-plugin')
module.exports = {
entry: "./src/index.js",
output: {
path: path.resolve (__dirname, 'dist'),
filename: "bundle.js"
},
mode: "development",
resolve: {
extensions: ['.js', '.jsx']
},
module: {
rules: [
{test: /\.(js|jsx)$/,
exclude: "/node_modules",
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env', '#babel/preset-react']
}
}},
{test: /\html$/,
use: [
{loader: 'html-loader'}
] },
{test: /\.sa[ac]ss$/,
use: ['css-loader',
'style-loader',
'sass-loader']}
]
},
plugins: [
new HtmlWebpackPlugin ({
inject: true,
template: "./public/index.html",
filename: '/menu.html'
}), new MiniCssExtractPlugin ({
filename: "[name].css"
})
]
}
index.html
<title>Document</title>
</head>
<body>
<div id="Hello"> </div>
</body>
</html>
I found the solution. It was the filename config. Was /menu.html. So when localhost was with /menu.html, React render the h1 element.
So, to make render I only have to change /menu.html for index.html in the filename config, refresh and was done!

React-Router subroutes not displaying

It seems that when webpack builds the file the output can only see the maincard div and none of the contents therein. I'm not sure what's missing as when this is run as npm react-scripts start it works fine. I'm not sure what i'm missing from webpack for this to render correctly. I'm trying to load this into an S3 bucket so it has to be packed with the webpack.
import React from 'react';
import { connect } from 'react-redux';
import { Route, withRouter } from 'react-router-dom';
import { fetchUserList } from "../actions/UserActions";
import { fetchSkillList } from "../actions/SkillActions";
import WelcomeCard from "./WelcomeCard";
import UserSearchCard from "./UserSearchCard";
import AddUserCard from './AddUserCard';
import '../styles/MainCard.css';
class MainCard extends React.Component {
componentDidMount() {
this.props.fetchUserList();
this.props.fetchSkillList();
}
render() {
return (
<div className="main_card">
<Route exact path='/' component={WelcomeCard}/>
<Route path='/list' component={UserSearchCard}/>
<Route path='/new' component={AddUserCard}/>
</div>
);
}
}
const mapDispatchToProps = dispatch => {
return {
fetchUserList: () => dispatch(fetchUserList()),
fetchSkillList: () => dispatch(fetchSkillList())
}
};
export default withRouter( connect(undefined, mapDispatchToProps)(MainCard) );
Webpack Config:
let path = require('path');
let webpack = require('webpack');
const publicPath = '/dist/build/';
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
module.exports = {
//Content
entry: './src/index.js',
mode: 'development',
// A SourceMap without column-mappings ignoring loaded Source Maps.
devtool: 'cheap-module-source-map',
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('development')
}
}),
//simplifies creation of HTML files to serve your webpack bundles. This is especially useful for webpack bundles that include a hash in the filename which changes every compilation. You can either let the plugin generate an HTML file for you, supply your own template using lodash templates or use your own loader.
new HtmlWebpackPlugin({
title: 'Talent Identification Manager'
}),
//Auto replacement of page when i save some file, even css
new webpack.HotModuleReplacementPlugin(),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
],
output: {
path: path.join(__dirname, publicPath),
filename: 'main.bundle-0.0.1.js',
publicPath: "/",
sourceMapFilename: 'main.map',
},
devServer: {
port: 3000,
host: 'localhost',
//Be possible go back pressing the "back" button at chrome
historyApiFallback: true,
noInfo: false,
stats: 'minimal',
publicPath: publicPath,
contentBase: path.join(__dirname, publicPath),
//hotmodulereplacementeplugin
hot: true
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules(?!\/webpack-dev-server)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-2'],
plugins: ['syntax-decorators']
}
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader'
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
}
]
}
}
React Router doesn't know that you want to treat /talentidbucket as the base of your site, so you have explicitly tell it so by passing the base path as the basename prop of the BrowserRouter component in production.
class App extends React.Component {
render() {
return (
<BrowserRouter basename="/talentidbucket"> {/* ... */} </BrowserRouter>
);
}
}

React Router wildcard not being matched [duplicate]

I have the following webpack config file:
var webpack = require('webpack');
var path = require('path');
var BUILD_DIR = path.resolve(__dirname, 'src/client/public');
var APP_DIR = path.resolve(__dirname, 'src/client/app');
var config = {
entry: [
APP_DIR + '/config/routes.jsx',
'webpack/hot/dev-server',
'webpack-dev-server/client?http://localhost:8080'
],
output: {
publicPath: 'http://localhost:8080/src/client/public/'
},
module : {
loaders : [
{
test: /\.jsx?$/,
loader: 'babel-loader',
include: APP_DIR,
exclude: /node_modules/,
query: {
presets: ['es2015']
}
},
{
test: /\.scss$/,
loaders: [ 'style', 'css', 'sass' ]
},
{
test: /\.json$/,
loader: "json-loader"
}
]
}
};
module.exports = config;
all I am trying to do is run my app on localhost, however when I hit: "http://localhost:8080/src/client/home" (as per my routes.jsx and after running webpack-dev-server)
import React from 'react';
import { Route, Router, browserHistory } from 'react-router';
import ReactDOM from 'react-dom';
import Wrapper from './../components/wrapper.jsx';
import Home from './../components/home.jsx';
import Projects from './../components/projects.jsx';
import SingleProject from './../components/projectContent/singleProject.jsx';
import About from './../components/aboutUs.jsx'
ReactDOM.render((
<Router history={browserHistory} >
<Route path="/" component={Wrapper} >
<Route path="home" component={Home} />
<Route path="projects" component={Projects} />
<Route path="projects/:id" component={SingleProject} />
<Route path="about" component={About} />
</Route>
</Router>
), document.getElementById('app'));
I get
"Cannot GET /src/client/home".
First thing you have mentioned in your routes as the home component to have path /home. So you need to visit http://localhost:8080/home. Also if you try to access this url directly, it will give you this error since you are using browserHistory. If you want you can use hashHistory or HashRouter in react-router v4, in which case you will need to visit http://localhost:8080/#/home. If you want to continue using browserHistory or BrowserRouter as in react-router v4, then you will need to add historyApiFallback: true in you webpack
var webpack = require('webpack');
var path = require('path');
var BUILD_DIR = path.resolve(__dirname, 'src/client/public');
var APP_DIR = path.resolve(__dirname, 'src/client/app');
var config = {
entry: [
APP_DIR + '/config/routes.jsx',
'webpack/hot/dev-server',
'webpack-dev-server/client?http://localhost:8080'
],
output: {
publicPath: 'http://localhost:8080/src/client/public/'
},
devServer: {
historyApiFallback: true
},
module : {
loaders : [
{
test: /\.jsx?$/,
loader: 'babel-loader',
include: APP_DIR,
exclude: /node_modules/,
query: {
presets: ['es2015']
}
},
{
test: /\.scss$/,
loaders: [ 'style', 'css', 'sass' ]
},
{
test: /\.json$/,
loader: "json-loader"
}
]
}
};
module.exports = config;
You need to add this in your webpack settings:
devServer: {
historyApiFallback: true,
},
And start your server like this:
webpack-dev-server --config webpack.config.js
Because you want React-Route to handle the route instead of your server. So no matter what the url is it should goes to index.html.

Babel Webpack ES6 React : require is not defined

Despite heavy efforts to my knowledge, I am not able to get:
ReactDebugTool.js:14 Uncaught ReferenceError: require is not defined(…)
I have written a webpack config as below:
// webpack.config.babel.js
import path from 'path';
import webpack from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
const sharedConfiguration = {
cache: true,
context: __dirname,
entry: {
app: ["./example/example.js"],
styles: ["./example/example.scss"]
},
devtool: "source-map",
resolve: {
extensions: ["", ".js"]
},
module: {
preLoaders: [
{ test: /\.js$/, loaders: ["eslint", "eslint-loader"] }
],
loaders: [
{ test: /\.js$/, loader: "babel-loader", exclude: /node_modules/, query: { presets: ["es2015", "stage-0", "react"], plugins: ['transform-runtime'] } },
{ test: /\.(scss|sass)$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader?sourceMap!resolve-url-loader!sass-loader?sourceMap") },
{ test: /\.html$/, loaders: ["html-loader"] },
{ test: /\.(jpg|png|woff|woff2|eot|ttf|svg|ico)$/, loader: "file-loader?name=[name]-[hash].[ext]" },
{ test: /\.(json|geojson)$/, loader: "json-loader" }
],
noParse: /ol\.js/
},
eslint: {
configFile: './.eslintrc'
}
};
const developmentConfiguration = {
watch: true,
output: {
pathinfo: true,
filename: "[name]-[chunkhash].js",
path: path.resolve("./.tmp")
},
devServer: {
port: 8081
},
plugins: [
new ExtractTextPlugin("[name]-[chunkhash].css"),
new webpack.optimize.CommonsChunkPlugin({
name: "vendor"
}),
new HtmlWebpackPlugin({
template: "./example/example.ejs",
inject: false
})
]
};
let environmentConfiguration = developmentConfiguration;
const configuration = {
...sharedConfiguration,
...environmentConfiguration
};
export default configuration;
And my project holds a folder structure like this.
// example.ejs
<!DOCTYPE html>
<html>
<head>
<title>Editor</title>
<script src="<%= htmlWebpackPlugin.files.chunks.vendor.entry %>"></script>
<link rel="stylesheet" href="<%= htmlWebpackPlugin.files.chunks.styles.css[0] %>">
</head>
<body>
<div id="root"></div>
<script src="<%= htmlWebpackPlugin.files.chunks.app.entry %>"></script>
</body>
</html>
// example.js
import React from 'react';
import ReactDOM from 'react-dom';
import Hello from '../source/index';
ReactDOM.render(<Hello />, document.getElementById('root'));
// source/index.js
import React, {Component} from 'react';
export default class Hello extends Component {
render () {
return (
<div>
Hello
</div>
);
}
}
Most of the articles I referred, indicated to CommonsChunkPlugin I tried rectifying it, but was in vain. Any help would be appreciated.

react client side rendering error cannot get /

I am attempting to learn react and I am coming to some issues when attempting client side routing. Please let me know if you see the mistake I have in my files listed.The error I keep getting on the browser page is
Cannot GET /
The error I see in my console is:
live.bundle.js:14 GET http://localhost:8080/ 404 (Not Found)
Here are my files:
webpack.config.js
var webpack = require('webpack');
module.exports = {
entry: [
'webpack/hot/only-dev-server',
'./js/app.js'
],
output: {
path: __dirname + '/build',
filename: "bundle.js"
},
module: {
loaders: [
{ test: /\.js?$/, loaders: ['react-hot', 'babel', 'babel-loader'], exclude: /node_modules/ },
// { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' },
{ test: /\.css$/, loader: "style!css" }
]
},
devServer: {
contentBase: "./src/www",
noInfo: true,
hot: true,
inline: true
},
plugins: [
new webpack.NoErrorsPlugin()
]
};
.babelrc
{
"presets": ["es2015", "react"]
}
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>New React App</title>
</head>
<body>
<section id="react"></section>
<script src="/build/bundle.js"></script>
</body>
</html>
/js/app.js
import React from 'react';
import Router from 'react-router';
import {DefaultRoute, Link, Route, RouteHandler} from 'react-router';
import LoginHandler from './components/Login.js';
class App extends React.Component{
render() {
return(
<div className="nav">
<Link to="app">Home</Link>
<Link to="login">Login</Link>
{/* Important Part */}
<RouteHandler/>
</div>
);
}
}
let routes = (
<Route name="app" path="/" handler={App}>
<Route name="login" path="/login" handler={LoginHandler}/>
</Route>
);
ReactDOM.run(routes, function (Handler) {
React.render(<Handler/>, document.body);
});
/js/components/Login.js
import React from 'react';
class Login extends React.Component{
render() {
return(
<div>Welcome to login</div>
);
}
}
export default Login;
I appreciate the help.
Here is my webpack.config.js file updated according to #Frederick Mfinanga
var webpack = require('webpack');
module.exports = {
entry: [
'webpack/hot/only-dev-server',
'./js/app.js',
'webpack-dev-server/client?localhost:8080'
],
output: {
path: __dirname + '/build',
filename: "bundle.js"
},
module: {
loaders: [
{ test: /\.js?$/, loaders: ['react-hot', 'babel', 'babel-loader'], exclude: /node_modules/ },
// { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' },
{ test: /\.css$/, loader: "style!css" }
]
},
devServer: {
// contentBase: "./src/www",
noInfo: true,
hot: true,
inline: true
},
plugins: [
new webpack.NoErrorsPlugin(),
new webpack.HotModuleReplacementPlugin()
]
};
remove
contentBase: "./src/www",
from your devServer config. This will by default serve the files in your current directory. which i believe is what you are looking for and where your index.html lives? correct?

Categories