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

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>

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

react app with webpack built from scratch is not loading an image in css

I built a simple react app that uses webpack and babel. I am having trouble loading my images. My basic folder structure:
root:
webpack.config.js
package.json
public:
index.html
src:
800x600-1x2x.jpg
App.css
App.js
index.js
App.js is boilerplate code:
import React, { Component} from "react";
import {hot} from "react-hot-loader";
import "./App.css";
class App extends Component{
render(){
return(
<div className="App">
<h1> Hello, World!! </h1>
</div>
);
}
}
export default hot(module)(App);
App.css is where I am loading an image into my background:
.App {
margin: 1rem;
font-family: Arial, Helvetica, sans-serif;
background-image: url("./800x600-1x2x.jpg");
border: 1px solid red;
}
webpack.config.js: i've tried using url-loader instead of file-loader that did not work
const path = require("path");
const webpack = require("webpack");
module.exports = {
entry: "./src/index.js",
mode: "development",
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
loader: "babel-loader",
options: { presets: ["#babel/env"] }
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
},
{
test: /\.(png|jpe?g|gif)$/i,
use: "file-loader"
}
]
},
resolve: { extensions: ["*", ".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/",
hotOnly: true
},
plugins: [new webpack.HotModuleReplacementPlugin()]
};
Looking through chrome sources I can see webpack:// is doing something with the image if I click on the 800x600-1x2x.jpg I get this code:
__webpack_require__.r(__webpack_exports__);
/* harmony default export */ __webpack_exports__["default"] = (__webpack_require__.p + "0e5cf6190f4b1586fb587bc9e9577981.jpg");
Selecting App element and looking at the css rules I see this crossed out:
background-image: url([object Module]);
Things that I tried and did not work:
placing the image in the public folder that didn't do anything.
creating a dist folder and putting the image in that folder.
installed html-loader and included it in webpack:
{
test: /\.html$/,
loader: 'html-loader'
},
installed resolve-url-loader and included it in webpack:
{
test: /\.css$/,
loader: ["style-loader", "css-loader", "resolve-url-loader"]
},
Other info:
I am also not building a bundle.js the webpack is compiling at runtime.
I am using this to run my webpack: webpack-dev-server --mode development
I looked around other stackoverflow answers and didn't see anything that worked for me. What am I missing?
It looks like the relative paths are incorrect. Your assets should be placed inside your source folder, not in the root.
This structure should work with your current webpack config
root:
webpack.config.js
package.json
public:
index.html
src:
index.js
800x600-1x2x.jpg
App.css
App.js
So I dug deep in webpacks documentation and other online projects for a whole day yesterday only to realize that my dependencies were out of date... However all the effort I put in was not a lost cause, I created a much better and cleaner set up that will work with a react app and load css and images. Enjoy. -.-
package.json:
"devDependencies": {
"#babel/cli": "^7.1.0",
"#babel/core": "^7.1.0",
"#babel/preset-env": "^7.1.0",
"#babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.2",
"css-loader": "^3.4.0",
"file-loader": "^5.0.2",
"html-webpack-plugin": "^3.2.0",
"style-loader": "^1.1.1",
"url-loader": "^3.0.0",
"webpack": "^4.41.4",
"webpack-cli": "^3.1.1",
"webpack-dev-server": "^3.10.1"
},
"dependencies": {
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-hot-loader": "^4.3.11"
}
folder structure:
public
800x600-1x2x.jpg
index.html
src
App.css
App.js
index.js
webpack.config.js:
const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, "dist"),
filename: "bundle.js",
publicPath: "/"
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loader: "babel-loader",
options: { presets: ["#babel/env"] }
},
{
test: /\.css$/,
loader: ["style-loader", "css-loader"]
},
{
test: /\.(jpg)$/i,
loader: "url-loader"
}
]
},
devServer: {
hot: true,
open: true,
port: 3000,
proxy: {"/": "http://localhost:5000"},
contentBase: path.resolve(__dirname, "public"),
publicPath: "/"
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'public/index.html'),
inject: true
})
]
};
To make a css file work one has to import it inside your .js
Example my index.js:
import "./App.css"
import App from "./App.js"
ReactDOM.render(<App/>, document.getElementById("root"));
From there my css file loads an image through my directory path:
background: url("../public/800x600-1x2x.jpg");
Loading an image in html through the img tag is as usual(warning below):
<img src="800x600-1x2x.jpg">
Warning: the img tag wont load an image when using a proxy with no real backend.
However, we are using react components so we can/should load an image inside our components jsx.
First import the image and then use the image tag. Example:
import background from '../public/800x600-1x2x.jpg'
const App = () => <img src={background}></img>

React index.html rendered but react component does not

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.

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.

Categories

Resources