React index.html rendered but react component does not - javascript

i couldn't figure out why ReactDOM does't render my simple component but seems to keep and render just the plain index.html
package.json
{
"name": "client2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "babel-node buildScripts/server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.16.3",
"path": "^0.12.7"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.8.3",
"webpack-dev-middleware": "^3.1.3"
},
"babel": {
"presets": [
"es2015",
"react"
],
"env": {
"presets": [
"react-hmre"
]
}
}
}
webpack.config.dev.js
import webpack from 'webpack'
import path from 'path'
const HtmlWebpackPlugin = require('html-webpack-plugin');
export default {
devtool: 'inline-source-map',
entry: [
path.resolve(__dirname, 'src/index.js')
],
output: {
path: path.resolve(__dirname, 'src'),
publicPath: '/',
filename: 'bundle.js'
},
module:{
rules:[
{test: /\.js$/ , loader:'babel-loader', exclude: '/node_modules/'},
{test: /\.jsx$/ , loader:'babel-loader', exclude: '/node_modules/'}
]
},
plugins:[
new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html',
inject: 'body'
})
]
}
buildScript/server.js
import express from 'express';
import path from 'path';
import webpack from 'webpack';
import config from '../webpack.config.dev';
const compiler = webpack(config);
/* var express = require('express')
var path = require('path') */
const port = 8081;
const app = express();
app.listen(port, function (error) {
if(error) {
console.log(error);
}
});
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, '../src/index.html'));
});
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
constructor(){
super();
console.log("App Hello")
}
render(){
return(
<div>
<h1>Howdy from React!</h1>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('root'));
src/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hey!</title>
</head>
<body>
<div id="root"></div>
<h1>Hello World!</h1>
</body>
</html>
The only response i get is
With no logs from my index.js react "App".
I've been trying several solutions, none happened aside from my express server not working. What might be the problem here ? Thank you very much !

As I wrote in comment, you should include your js
<html lang="en">
<head>
<title>Hey!</title>
</head>
<body>
<div id="root"></div>
<h1>Hello World!</h1>
<script src="/bundle.js"></script>
</body>
</html>

Your html file needs to link to bundle.js
<script src="/bundle.js"></script>

Thanks for Leo Odishvili and Ben West for helping above - the answer is really adding <script src="/bundle.js"></script> to the index.html
The only change was to
change /bundles.js to "./webservice_entrypoint/bundle.js"as webservice_entrypoint would be the url path to my react app.
Thanks everyone !

Also you can check the "html-webpack-plugin" and add the plugin to the "plugins" configuration of the webpack.config.js, this will allow you to use any template html file from inside your src directly and bundle it in the dist/ folder with the included script tag already compiled and added. It is really an useful plugin.

Related

How do you use webpack-merge and react?

I have been trying to make a webpack config for a react based app, it was working before I started using webpack-merge and had the single webpack.config.js file. I have done a lot of reading and I have not been able to find a solution and was wondering if there is a way for me to have a split webpack config.
Any help would be much appreciated!
The error I am getting is:
ERROR in ./src/index.js 8:4
Module parse failed: Unexpected token (8:4)
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
|
| ReactDOM.render(
> <App title={title} />,
| document.getElementById('app')
| );
webpack 5.19.0 compiled with 1 error in 17 ms
i 「wdm」: Failed to compile.
My webpack config files:
webpack.common.js
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('html-webpack-plugin');
module.exports = {
entry: path.resolve(__dirname, '..', './src/index.js'),
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['#babel-loader'],
},
],
},
resolve: {
extensions: ['*', '.js', '.jsx'],
},
output: {
path: path.resolve(__dirname, '..', './dist'),
filename: 'bundle.js',
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: path.resolve(__dirname, '..', './src/index.html')
}),
],
devServer: {
contentBase: path.resolve(__dirname, '..', './dist'),
hot: true,
},
};
webpack.config.js
const { merge } = require('webpack-merge');
const commonConfig = require('./webpack.common.js');
module.exports = ({ env }) => {
const envConfig = require(`./webpack.${env}.js`);
return merge(commonConfig, envConfig);
};
webpack.dev.js
module.exports = {
mode: 'development',
devtool: 'eval-source-map',
};
webpack.prod.js
module.exports = {
mode: 'production',
devtool: 'source-map',
};
My other files:
App.js
import React from "react";
const App = ({ title }) =>
<div>{title}</div>;
export default App;
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Hello World!</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="">
</head>
<body>
<div id='app'></div>
</body>
</html>
index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "../App";
ReactDOM.render(
<App title={title} />,
document.getElementById('app')
);
module.hot.accept();
.babelrc
{
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
}
package.json
...
"scripts": {
"start": "webpack serve --config build-utils/webpack.dev.js --env env=dev",
"build": "webpack --config build-utils/webpack.prod.js --env env=prod",
"test": "echo \"Error: no test specified\" && exit 1"
},
...
"devDependencies": {
"#babel/core": "^7.12.10",
"#babel/preset-env": "^7.12.11",
"#babel/preset-react": "^7.12.10",
"babel-cli": "^6.26.0",
"babel-loader": "^8.2.2",
"clean-webpack-plugin": "^3.0.0",
"html-webpack-plugin": "^4.5.1",
"react-hot-loader": "^4.13.0",
"webpack": "^5.19.0",
"webpack-cli": "^4.4.0",
"webpack-dev-server": "^3.11.2",
"webpack-merge": "^5.7.3"
},
"dependencies": {
"react": "^17.0.1",
"react-dom": "^17.0.1"
}

SyntaxError in ./index.html

I'm trying to convert my create-react-app to a Webpack compatible app.
I can't understand clearly what I'm done and I often get into an error:
ERROR in ./index.html
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: /mnt/c/Users/.../index.html: Unexpected token (1:0)
> 1 | <!doctype html>
| ^
2 | <html>
3 | <head>
4 | <title>Getting Started</title>
at Object._raise [...]
This happens after launching npm start
This is my configuration:
Structure
index.html
webpack.config.js
babelrc
src/index.js
package.json
./index.html
<!doctype html>
<html>
<head>
<title>Getting Started</title>
<script src="https://unpkg.com/lodash#4.16.6"></script>
</head>
<body>
<script src="./src/index.js"></script>
</body>
</html>
./src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
serviceWorker.unregister();
./webpack.config.js
const webpack = require('webpack');
const path = require('path');
const config = {
entry: [
'react-hot-loader/patch',
'./index.html'
],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$|jsx$|html/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['#babel/preset-env', '#babel/react']
}
}
]
},
resolve: {
extensions: [
'.js',
'.jsx',
'.html'
],
alias: {
'react-dom': '#hot-loader/react-dom'
}
},
devServer: {
contentBase: './dist'
}
};
module.exports = config;
Finally, my ./.babelrc
{
"plugins": ["#babel/transform-react-jsx"],
"ignore": [
"foo.js",
"bar/**/*.js"
]
}
I've this dependencies in my package.json:
"devDependencies": {
"#babel/core": "^7.11.6",
"#babel/preset-env": "^7.11.5",
"#babel/preset-es2015": "^7.0.0-beta.53",
"#babel/preset-react": "^7.10.4",
"#babel/preset-typescript": "^7.10.4",
"#hot-loader/react-dom": "^17.0.0-rc.2",
"babel-loader": "^8.1.0",
"babel-plugin-import": "^1.13.0",
"css-loader": "^4.3.0",
"react-hot-loader": "^4.5.3",
"style-loader": "^1.2.1",
"webpack": "^4.44.2",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0"
}
You're using a javascript loader for your html, this is not going to work.
You should use the html-loader instead

unexpected token < bundle js in reactjs app

i am creating js app from scratch , and this is my webpack config file
import path from 'path';
export default {
entry: path.join(__dirname,'/client/index.js'),
output: {
path: '/'
},
module: {
loaders: [
{
test: /\.js$/,
include: path.join(__dirname,'client'),
loaders: ['babel-loader'],
}
]
},
resolve: {
extensions: ['*', '.js']
}
}
this is my .babelrc file :
{
"presets": ["es2015", "react"]
}
this is my index.html file :
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="root"></div>
<script src="bundle.js"></script>
</body>
</html>
this is my client/index.js
import React from 'react';
import { render } from 'react-dom';
import App from './Component/App';
render(<App />, document.getElementById("root"));
this is my App component
import React from 'react';
export default () => {
return <h1>Hello from react</h1>;
}
this is dependencies used by the app
{
"dependencies": {
"express": "^4.15.3",
"react": "^15.6.1",
"react-dom": "^15.6.1"
},
"devDependencies": {
"babel-cli": "^6.24.1",
"babel-loader": "^7.1.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"nodemon": "^1.11.0",
"webpack": "^3.2.0",
"webpack-dev-middleware": "^1.11.0",
"webpack-dev-server": "^2.5.1"
}
}
build is success but i got an error Unexpected token < bundle.js:1 after running the app,
anyone know what is causing the error? thank
Add filename to your webpack.config within output:
entry: path.join(__dirname,'/client/index.js'),
output: {
path: '/',
filename: 'bundle.js'
}
basically this is happening because in your index.html you are importing bundle.js
<script src="bundle.js"></script>
but your webpack is outputting index.js, by adding the filename attribute, webpack will now output bundle.js

Facing some issues with ReactJS first program

I just started learning ReactJS, I am following this tutorials here.
egghead.io I just completed its first video and developed an app as shown in video, But some how I can see the html part but failed to load the dynamic content coming from the App.js Below is my code:
App.js
import React from 'react';
class App extends React.Component {
// always expected to return
render() {
return '<div><h4>Hello World of ReactJS</h4></div>'
}
}
export default App;
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ReactJS Tutorial</title>
</head>
<body>
<h1>ReactJS First Project</h1>
<div id="app">
</div>
<script src="index.js"></script>
</body>
</html>
main.js:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render('<App/>' , document.getElementById('app'));
package.json
{
"name": "App",
"version": "1.0.0",
"description": "First application of ReactJS",
"private": true,
"main": "index.js",
"scripts": {
"start": "webpack-dev-server"
},
"author": "AD",
"license": "Apache",
"dependencies": {
"babel-core": "^6.13.1",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.13.1",
"babel-preset-react": "^6.11.1",
"react": "^15.3.0",
"react-dom": "^15.3.0"
},
"devDependencies": {
"webpack-dev-server": "^1.9.0"
}
}
webpack.config.js:
module.exports = {
entry: "./main.js",
output: {
path: "./",
fileName: "index.js"
},
devServer: {
inline: true,
port: 3333
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
Would need some help to run it, not sure. I have installed everything as asked in the video, I am using node 6.2.2.
In your main.js, change:
ReactDOM.render('<App/>' , document.getElementById('app'));
to
ReactDOM.render(<App/>, document.getElementById('app'));
The quotes are the problem. You want to render your imported component, not some String. Also I would be interested if you got a warning in the console.

Unable to load ReactJS resource in the browser using Babel and Webpack

I'm trying to learn ReactJS by running a basic program.
webpack.config.js
var config = {
entry: './main.js',
output: {
path: './',
filename: 'index.js'
},
devServer: {
inline: true,
port: 8080
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
module.experts = config;
package.json
{
"name": "reactapp",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --hot"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-core": "^6.11.4",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.9.0",
"babel-preset-react": "^6.11.1",
"react": "^15.2.1",
"react-dom": "^15.2.1",
"webpack": "^1.13.1",
"webpack-dev-server": "^1.14.1"
}
}
App.jsx
import React from 'react';
class App extends React.Component {
render() {
return (
<div>
"Hello, world."
</div>
);
}
}
export default App;
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App />, document.getElementById('app'));
index.html
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset="utf-8">
<title>React App</title>
</head>
<body>
<div id = "app"></div>
<script type="text/javascript" src = "index.js"></script>
</body>
</html>
On starting the server, I see an empty page with no contents. The HTML page is there but the part which is to be added to the DOM by React can't be seen.
index.js is set as the file which will contain our bundled app but the browser's console shows 'Faile to load resource index.js(404)' error. If I change the src attribute of script tag in HTML to main.js, I get a SyntaxError with the import statement.
I suspect the problem is with not correctly linking Babel or some other dependency with my package.
Inside webpack.config.js there is typo, must be exports instead of experts
module.exports = config;
^
in this case you don't export config from webpack.config.js, and webpack doesn't know about your custom configuration and uses default config.
I think the webpack.config.jswill be like
devtool: 'eval',
entry: './src/index',
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/',
},
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel'],
exclude: /node_modules/,
include: __dirname,
}],
}
and the <script>
<script type="text/javascript" src = "/static/bundle.js"></script>

Categories

Resources