npm dev run generates huge main.js file - javascript

I have a Django application and trying to rewrite my JS frontend to React. I found some tutorial how to organize the structure of React app:
frontend/
static/frontend/main.js/main.js
src/
index.js
components/App.js
package.json
{
"name": "frontend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"presets": [
"#babel/preset-env",
"#babel/preset-react"
],
"scripts": {
"dev": "webpack --mode development ./src/index.js --output-path ./static/frontend/main.js",
"build": "webpack --mode production ./src/index.js --output-path ./static/frontend/main.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.20.12",
"#babel/preset-env": "^7.20.2",
"#babel/preset-react": "^7.18.6",
"babel-loader": "^9.1.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"webpack": "^5.75.0",
"webpack-cli": "^5.0.1"
},
"dependencies": {
"fs-promise": "^2.0.3"
}
}
webpack.config.js
module.exports = {
devtool: false,
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: { presets: ['#babel/env','#babel/preset-react'] },
}
}
]
}
};
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Django REST with React</title>
</head>
<body>
<h1>Anything</h1>
<div id="app">
<!-- React will load here -->
</div>
</body>
{% load static %}
<script src="{% static "frontend/main.js/main.js" %}"></script>
</html>
sample code in App.js
import React from 'react';
import ReactDOM from 'react-dom';
function App() {
const [value, setValue] = React.useState(0);
function increment() {
setValue(value + 1);
}
return (
<div className="app">
<h1>{value}</h1>
<button onClick={increment}>+1</button>
</div>
);
}
ReactDOM.render(
<div>
<App />
</div>,
document.getElementById("root")
);
const container = document.getElementById("app");
ReactDOM.render(<App />, container);
If I got it right, any React component imported in index.js will be compiled to js code in main.js which is included to index.html. I created a simple code in App.js just to try it and it does work, but it generates a 30k lines main.js file. Is it normal? I guess it shouldn't be like this since it consumes much more resources than my 400-lines js code, so what am I doing wrong ?part of code in main.js

Related

React Component not loading with Webpack and Babel Beginner's level

I am trying to understand how React, Babel and Webpack interact with each other, but I get the following error: Uncaught TypeError: Super expression must either be null or a function. The CSS is rendering just fine but the HTML isn't, though I was able to see it in the console (view image below).
Any suggestions?
package.json
{
"name": "react-raw",
"version": "1.0.0",
"description": "",
"main": "index.js",
"babel": {
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
},
"scripts": {
"start": "webpack-dev-server --open"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"react": "^16.8.4",
"react-dom": "^16.8.4"
},
"devDependencies": {
"#babel/core": "^7.4.0",
"#babel/preset-env": "^7.4.1",
"#babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.5",
"css-loader": "^2.1.1",
"html-webpack-plugin": "^3.2.0",
"style-loader": "^0.23.1",
"webpack": "^4.29.6",
"webpack-cli": "^3.3.0",
"webpack-dev-server": "^3.2.1"
}
}
index.js
var React = require("react");
var ReactDOM = require("react-dom");
require("./index.css");
class App extends React.Component() {
render() {
return <div>Hello Christian!!</div>;
}
}
ReactDOM.render(<App />, document.getElementById("app"));
webpack.config.js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin"); //installed via npm
//const webpack = require("webpack"); //to access built-in plugins
module.exports = {
entry: "./app/index.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "index_bundle.js"
},
module: {
rules: [
{ test: /\.(js)$/, use: "babel-loader" },
{ test: /\.css$/, use: ["style-loader", "css-loader"] }
]
},
mode: "development",
plugins: [new HtmlWebpackPlugin({ template: "app/index.html" })]
};
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>React Raw</title>
</head>
<body>
<div id="app"></div>
</body>
</html>
Your problem is with the signature of your class component:
class App extends React.Component() {
render() {
return <div>Hello Christian!!</div>;
}
}
This is how you need to declare it:
class App extends React.Component{
render() {
return <div>Hello Christian!!</div>;
}
}
Note the extra () i omitted
You can read more about classes in here

Simple react component not accepting arrow function

I'm trying to create my first component in react but I keep getting error. It results in not showing button element on the website at all. Here are my files:
ERROR in ./src/js/components/presentational/Button1.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: Unexpected token (3:13)
1 | import React, { Component } from "react";
2 | class Button1 extends React.Component {
> 3 | handleClick = () => {
| ^
4 | console.log("dupa");
5 | };
6 | render() {
./src/js/components/presentational/Button1.js
import React, { Component } from "react";
class Button1 extends React.Component {
handleClick = () => {
console.log("dupa");
};
render() {
return (
<button onclick={this.props.handleClick}>
Button
</button>
);
}
}
export default Button1;
./src/js/components/container/FormContainer.js
import React, { Component } from "react";
import ReactDOM from "react-dom";
import Button1 from "../presentational/Button1";
class FormContainer extends Component {
render() {
return (
<Button1 />
);
}
}
export default FormContainer;
const wrapper = document.getElementById("create-article-form");
wrapper ? ReactDOM.render(<FormContainer />, wrapper) : false;
./src/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" >
<title>How to set up React, Webpack, and Babel</title>
</head>
<body>
<div class="container">
<div class="row mt-5">
<div class="col-md-4 offset-md-1">
<p>Create a new article</p>
<div id="create-article-form">
<!-- form -->
</div>
</div>
</div>
</div>
</body>
</html>
EDIT
I thought I was using babel. Do I need some additional step for transpilation? Currently I'm using only
npm start
This is my package.json:
{
"name": "front-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --open --mode development",
"build": "webpack --mode production",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-preset-env": "^1.7.0",
"babel-preset-latest": "^6.24.1",
"babel-preset-react": "^6.24.1",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"prop-types": "^15.6.2",
"react": "^16.4.2",
"react-dom": "^16.4.2",
"webpack": "^4.16.5",
"webpack-cli": "^3.1.0",
"webpack-dev-server": "^3.1.5"
}
}
and this is my .babelrc
{
"presets": [
"react",
"env"
]
}
EDIT2:
Problem solved. As stated here it was because arrow functions are not included into standard right now. I had to run sudo npm install --save-dev babel-plugin-transform-class-properties and had to edit my .babelrc:
{
"presets": [
"react",
"env"
],
"plugins": [
["transform-class-properties", { "spec": true }]
]
}
You get the error because class properties (class Example { myProperty = 'foobar' }) is not a part of the language yet.
You need to add either a Babel plugin or preset for it to work. You could use the stage 2 preset.
.babelrc
{
"presets": [
"react",
"env"
"stage-2"
]
}
You can also do:
handleClick() {
// code here
}

React router page rendering issue

Learning React right now tried to use react-router for page routing, but because of some reasons I always see the blank page instead of rendered component.
I'm using webpack-dev-server as dev server.
Looking for your help and advices
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link href="dist/css/app.css">
</head>
<body>
<div id="root"></div>
<script src="dist/js/app.js"></script>
</body>
</html>
app.js
import React from 'react';
import ReactDOM from 'react-dom';
import {Router, Route, IndexRoute, hashHistory } from "react-router";
import App from './Pages/App';
import Archives from './Pages/Archives';
import Features from './Pages/Features';
import Settings from './Pages/Settings';
const app = document.getElementById('root');
// ReactDOM.render(<Layout/>, app);
ReactDOM.render(
<Router history={hashHistory}>
<Route path="/" component={App}>
<IndexRoute component={Features}/>
<Route path='archives' component={Archives}/>
<Route path='settings' component={Settings}/>
</Route>
</Router>
, app);
App component
import React from 'react';
import { Link } from 'react-router'
export default class App extends React.Component{
render(){
return (
<div>
<h1>App</h1>
<Link to="/archives">Archives</Link>
<Link to="/settings">Settings</Link>
{this.props.children}
</div>
);
}
}
package.json
{
"name": "Planner",
"version": "1.0.0",
"description": "",
"main": "webpack.config.js",
"dependencies": {
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-plugin-add-module-exports": "^0.2.1",
"babel-plugin-react-html-attrs": "^2.0.0",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"history": "^4.6.1",
"react": "^15.5.4",
"react-dom": "^15.5.4",
"react-router": "^4.1.1",
"webpack": "^2.4.1",
"webpack-dev-server": "^2.4.4"
},
"devDependencies": {},
"scripts": {
"dev": "webpack-dev-server --content-base --inline --hot",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
UPDATED:
Webpack config
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var path = require('path');
module.exports = {
context: path.join(__dirname, "src"),
devtool: debug ? "inline-sourcemap" : null,
entry: "./js/app.js",
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-0'],
plugins: ['react-html-attrs', 'transform-decorators-legacy', 'transform-class-properties'],
}
}
]
},
output: {
path: path.resolve(__dirname, 'dist/js'),
filename: "app.js",
publicPath: '/dist/js/'
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
],
};

after add component link error: Uncaught SyntaxError: Unexpected token export

i create test react project. Add modules and my packege.json look like:
{
"name": "untitled",
"version": "0.1.0",
"private": true,
"devDependencies": {
"babel-preset-node5": "^12.0.1",
"react-scripts": "0.9.5"
},
"dependencies": {
"babel-preset-stage-0": "^6.22.0",
"history": "^4.6.1",
"react": "^15.4.2",
"react-dom": "^15.4.2",
"react-native": "^0.42.3",
"react-router": "^4.0.0",
"react-router-config": "^1.0.0-beta.1",
"react-router-dom": "^4.0.0",
"react-router-native": "^4.0.0",
"webpack": "^2.2.1",
"webpack-dev-server": "^2.4.2"
},
"scripts": {
"start": "react-scripts start",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject",
"build": "babel input.js -o compiled.js"
}
}
and webpack.config.js
var config = {
entry: './index.js',
output: {
path:'/',
filename: 'index.js',
},
devServer: {
inline: true,
port: 8080
},
module: {
loaders: [
{
test: /\.js?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', "node5", "stage-1", 'react', "stage-0"]
}
}
]
}
};
module.exports = config;
in my component i import component Link from react-router-native and after this adding react show error 'Uncaught SyntaxError: Unexpected token export' but if i delete this string project work well. it's not the only component in the module, i can add any components like Promt, Route or Router. Why it's not work with Link?
This is code where error reproduced
import React from 'react';
import { Route, Router } from 'react-router';
import { Promt } from 'react-router';
import { Link } from 'react-router-native';
import logo from '../../logo.svg';
import './App.css';
class App extends React.Component {
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
export default App;
You need to update the regular expression for the test value in your web pack config to be test: /(\.js|\.jsx)$/
Right now you are telling webpack to only run .js files through babel loader, but you aren't telling it to also run .jsx files through babel loader.

I am getting a 404 error on my new Reactjs app, is it looking for a main.js file?

This app should be rendering what I have here (/Users/ldco2016/Projects/reactquiz/src/components/App.jsx:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
class App extends Component{
render(){
return(
<div>
APP
</div>
)
}
}
export default App
but instead I get a blank page and the Chrome Dev tools console is telling me this:
GET http://localhost:8080/app/js/main.js 404 (Not Found)
I know what that means but I am unclear as to whether it is trying to find the page I want to render or the main.js file.
/Users/ldco2016/Projects/reactquiz/package.json:
{
"name": "reactquiz",
"version": "1.0.0",
"description": "A Reactjs Quiz App",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Daniel Cortes",
"license": "ISC",
"devDependencies": {
"babel-core": "6.13.*",
"babel-loader": "6.2.*",
"webpack": "1.13.*"
},
"dependencies": {
"react": "^15.3.1",
"react-dom": "^15.3.1"
}
}
/Users/ldco2016/Projects/reactquiz/app/index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Reactjs Quiz</title>
</head>
<body>
<div id="app"></div>
<script src="js/main.js"></script>
</body>
</html>
ldco2016#DCortes-MacBook-Pro-3 ~/Projects/reactquiz/webpack.config.js:
module.export = {
entry: [
'./src/index.js'
],
output: {
path: __dirname,
filename: 'app/js/main.js'
},
module: {
loaders: [{
test: /\.jsx?$/,
loader: 'babel',
exclude: /node_modules/
}]
}
}
/Users/ldco2016/Projects/reactquiz/src/index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App.jsx';
ReactDOM.render(
<App />,
document.getElementById('app')
);
You need to run webpack to generate the main.js file. Make two changes to your file first in package.json add a script "start": "webpack --progress -p --config webpack.config.js --watch" and in your webpack.config.js change the loader to babel-loader.
P.S. Second change may not be required.
package.json
{
"name": "reactquiz",
"version": "1.0.0",
"description": "A Reactjs Quiz App",
"main": "index.js",
"scripts": {
"start": "webpack --progress -p --config webpack.config.js --watch"
},
"author": "Daniel Cortes",
"license": "ISC",
"devDependencies": {
"babel-core": "6.13.*",
"babel-loader": "6.2.*",
"webpack": "1.13.*"
},
"dependencies": {
"react": "^15.3.1",
"react-dom": "^15.3.1"
}
}
webpack.config.js
module.export = {
entry: [
'./src/index.js'
],
output: {
path: __dirname,
filename: 'app/js/main.js'
},
module: {
loaders: [{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/
}]
}
}
Now run webpack with command
npm run start
now open your localhost and the above should work.

Categories