"Uncaught Error: Cannot find module 'react'" keeps showing - javascript

I really wonder why it keeps showing me this error message
Uncaught Error: Cannot find module 'react'
although I have tried every single solution that I have found on the posts below:
Uncaught Error: Cannot find module "react"
"[ts] Cannot find module 'react'" in spite of "npm install"
Uncaught Error: Cannot find module 'react'
Cannot find module 'react'
These are the scripts I have put in my relevant files:
welcome.blade.php:
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel</title>
</head>
<body>
<div id="example"></div>
<script src="js/app.js"></script>
</body>
</html>
app.js:
require('./bootstrap');
require('./components/Example');
Example.js:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route, Switch, NavLink } from 'react-router-dom';
import Home from './Home';
import { Link } from 'react-router/lib/Link';
class Example extends Component{
render(){
return(
<BrowserRouter>
<div>
<NavLink to="/home">Home</NavLink>
<Switch>
<Route path="/home" component={Home}/>
</Switch>
</div>
</BrowserRouter>
)
}
}
export default Example;
if(document.getElementById('example')){
ReactDOM.render(<Example />, document.getElementById('example'));
}
Home.js:
import React, { Component } from 'react';
class Home extends Component{
render(){
return(
<div>
</div>
)
}
}
export default Home;
package.json:
{
"private": true,
"scripts": {
"dev": "npm run development",
"development": "mix",
"watch": "mix watch",
"watch-poll": "mix watch -- --watch-options-poll=1000",
"hot": "mix watch --hot",
"prod": "npm run production",
"production": "mix --production"
},
"devDependencies": {
"#babel/preset-react": "^7.12.13",
"axios": "^0.21.1",
"laravel-mix": "^6.0.11",
"lodash": "^4.17.19",
"postcss": "^8.1.14",
"resolve-url-loader": "^3.1.2",
"sass": "^1.32.6",
"sass-loader": "^8.0.2"
},
"dependencies": {
"#types/react": "^17.0.1",
"#types/react-dom": "^17.0.0",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-router": "^5.2.0",
"react-router-dom": "^5.2.0"
}
}
webpack.mix.js:
const mix = require('laravel-mix');
/*
|--------------------------------------------------------------------------
| Mix Asset Management
|--------------------------------------------------------------------------
|
| Mix provides a clean, fluent API for defining some Webpack build steps
| for your Laravel applications. By default, we are compiling the CSS
| file for the application as well as bundling up all the JS files.
|
*/
/* mix.js('resources/js/app.js', 'public/js')
.postCss('resources/css/app.css', 'public/css', [
//
]); */
mix.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css')
.react();
So, what is wrong in my code? Any idea?
P.S:
React JS version: 17.0.1
Node.js version: v15.7.0

This solved the issue for me.
Open up the terminal and type in
yarn add typescript --dev
if using npm type in
npm install typescript

Related

How to add React component to a website using babel

I'm trying to add a React component to a website using babel. Here's official React documentation tutorial but I could not make it work.
Here's my index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="theme-color" content="#000000"/>
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script src="https://unpkg.com/react#18/umd/react.production.min.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#18/umd/react-dom.production.min.js" crossorigin></script>
<script src="build/index.js" type="text/babel"></script>
</body>
</html>
Here's my src/index.js
import React from 'react'
import ReactDOM from 'react-dom/client'
function App() {
return (
<button>Like me!</button>
)
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
Here's my package.json
{
"name": "react-project",
"version": "1.0.0",
"description": "",
"main": "src/index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"#babel/cli": "^7.20.7",
"#babel/core": "^7.20.12",
"#babel/preset-react": "^7.18.6"
}
}
Then I run in terminal:
./node_modules/.bin/babel src --out-dir build --presets #babel/preset-react
It creates build/index.js which is added to my index.html:
import React from 'react';
import ReactDOM from 'react-dom/client';
function App() {
return /*#__PURE__*/React.createElement("button", null, "Like me!");
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render( /*#__PURE__*/React.createElement(App, null));
When I open index.html in browser - nothing happens, button does not appear.
This whole story works only if I add <script src="https://unpkg.com/#babel/standalone/babel.min.js"></script> to my index.html but this is not what I want.
What do I do wrong?
because babel only compiles jsx the esm syntax remains and you have nothing to deal with them (a compiler or esm itself with type='module' and cdn esm or importmap)
for starters use powerful tools like vite

Issue running React App on Django server with webpack

I am building a web-application using Django as the backend and want to implement a ReactJS framework frontend. Each application that I have as of now runs properly, independently of one another. I have also implemented webpack and it appears to configure properly, as it will run my ReactJS application on the localhost. Being new to webpack (and web-development in general) I am unsure how to get React to run on the Django local server (127.0.0.1:8000). I understand from the many forums I've read through that the javascript files need to be bundled and then read into the django app. Below are the relevant files:
package.json
{
"name": "package.json",
"version": "1.0.0",
"description": "This is the private repository for the USA Baseball analytics team.",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "SET NODE_ENV=development babel src -d lib",
"build-prod": "SET NODE_ENV=development babel src -d lib",
"start": "webpack-dev-server"
},
"repository": {
"type": "git",
"url": "git+https://github.com/USAB-Analytics/BaldEagle.git"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/USAB-Analytics/BaldEagle/issues"
},
"homepage": "https://github.com/USAB-Analytics/BaldEagle#readme",
"dependencies": {
"react": "^16.2.0",
"express": "^4.16.3",
"react-dom": "^16.4.1",
"react-sortable-hoc": "^0.8.3",
"yarn": "^1.7.0",
"react-prop-types": "^0.4.0",
"semantic-ui-react": "^0.77.1",
"react-router-dom": "^4.2.2"
},
"devDependencies": {
"babel": "^6.23.0",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.6.1",
"babel-preset-stage-1": "^6.24.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"html-webpack-plugin": "3.0.4",
"style-loader": "^0.19.1",
"css-loader": "^0.28.10",
"jsx-loader": "^0.13.2",
"react": "^16.4.0",
"webpack": "^4.10.2",
"webpack-bundle-tracker": "^0.3.0",
"webpack-cli": "^3.0.4",
"webpack-command": "^0.2.1",
"webpack-dev-server": "^3.1.4"
},
"keywords": []
}
webpack.config.js
var path = require("path");
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
//var BundleTracker = require('webpack-bundle-tracker')
const port = process.env.PORT || 3000;
process.env.NODE_ENV = 'production';
module.exports = {
mode: 'development',
entry: './frontend/src/index.js',
output: {
filename: 'bundle.[hash].js'
},
devtool: 'inline-source-map',
module: {
rules: [
// First Rule
{
test: /\.(js)$/,
exclude: /node_modules/,
use: ['babel-loader']
},
// Second Rule
{
test: /\.css$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader',
options: {
modules: true,
camelCase: true,
sourceMap: true
}
}
]
}
]
},
plugins: [
new HtmlWebpackPlugin({
title: 'Custom template',
template: './webapp/templates/webapp/home.html',
})
],
devServer: {
host: 'localhost',
port: port,
historyApiFallback: true,
open: true
}
};
frontend/src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './css/main.css';
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
import {HomePage} from './components/HomePage.js'
import {Bios} from './components/Bios.js'
import {Bio} from './components/Bio.js'
import {NavBar} from './components/NavBar.js'
import {TeamsList} from './components/TeamsList.js'
import {TOSBios} from './components/TOSBios.js'
import {NT18Bios} from './components/NT18Bios.js'
import {CNTBios} from './components/CNTBios.js'
import {NT15Bios} from './components/NT15Bios.js'
class App extends React.Component {
render(){
var styles = {
'marginLeft': '210px'
}
return (
<Router>
<div className="col-sm-10">
<NavBar />
<div style={styles}>
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/bios/:id" component={Bio} />
<Route path="/bios/" component={Bios} />
<Route path="/teams/tos/:id" component={Bio} />
<Route path="/teams/cnt/:id" component={Bio} />
<Route path="/teams/nt18/:id" component={Bio} />
<Route path="/teams/nt15/:id" component={Bio} />
<Route path="/teams/cnt/" component={CNTBios} />
<Route path="/teams/nt18/" component={NT18Bios} />
<Route path="/teams/nt15/" component={NT15Bios} />
<Route path="/teams/tos/" component={TOSBios} />
<Route path="/teams/" component={TeamsList} />
</Switch>
</div>
</div>
</Router>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
webapp/templates/webapp/home.html
<!-- {% extends "webapp/header.html" %} -->
{% load render_bundle from webpack_loader %}
<html>
<head>
<meta charset="UTF-8">
<title>React with Django</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
These shouldn't be running on the same server. If you are looking to connect them you should be able to create config files and say if production the url I hit is xx.com/users otherwise if it is development it is localhost:8000/users. Why would you need both to run on the same server?
We use django-webpack-loader to render our webpack bundles in a django template (for a Vue app but it's the same fundamental idea).
You've configured your webpack for development mode. It means that you run the webpack development server. But you need to build your front-end application into a bundle and then use this bundle for your server side. Just remove the devServer section. Also, you can erase this process.env.NODE_ENV = 'production'; and change the mode to production. This operation will set your process.env.NODE_ENV to production(https://webpack.js.org/concepts/mode/).
If you need to test your app in development mode you can add proxy to package.json with the address of your back-end and run front and back separately.
Solution:
Add an npm command:
"build:prod": "<your_build_command> && mv <output_path>/index.html <path_to_backend>/<app_name>/templates && mv <output_path>/* <path_to_backend>/static"
Add this to your Django app settings:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)

Embedded react component not rendered/loaded in html page. (webpack/babel)

I am trying to set up my first Webpack Babel React project.
Although the html code shows on various browsers (http://localhost:80), the embedded react component is not loaded. The following message can be read in the console
"Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
at invariant (transformed.js:304)"
Click here to see error image
Find below the different config and code files setting up this environment.
./app/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My first local App</title>
</head>
<body>
<div id='app'> </div>
<h1> Testing </h1>
</body>
</html>
./app/index.js
var React = require('react');
var ReactDOM = require('react-dom');
var App = require('../components/App');
ReactDOM.render(
<App />,
document.getElementById('app')
);
./components/App.js
import React from 'react';
import ReactDOM from 'react-dom';
export class App extends React.Component {
constructor(){
super();
console.log('Component has been constructed ')
}
render() {
return (
<div>
<h1>This is a simple test</h1>
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('app')
);
package.json
{
"name": "app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"deploy":"npm run build && npm run git-commit && npm run git-push",
"build": "webpack",
"start": "webpack-dev-server"
},
"author": "",
"license": "ISC",
"dependencies": {
"react": "^15.6.1",
"react-dom": "^15.6.1"
},
"devDependencies": {
"babel-core": "^6.25.0",
"babel-loader": "^7.1.1",
"babel-preset-react": "^6.24.1",
"html-webpack-plugin": "^2.30.1",
"webpack": "^3.4.1",
"webpack-dev-server": "^2.6.1"
}
}
.babelrc
{presets:["react"]}
webpack.config
var HTMLWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HTMLWebpackPlugin ({
template: __dirname + '/app/index.html',
filename: 'index.html',
inject: 'body'
});
module.exports = {
entry: __dirname + '/app/index.js' ,
module: {loaders: [ {test:/\.js$/, exclude:/node_modules/, loader:'babel-loader' } ]},
output: {filename: 'transformed.js', path: __dirname + '/build'},
plugins: [HTMLWebpackPluginConfig],
resolve : { extensions: [".js", ".jsx"] }
};
Thanks,
Sebastian
Looks like you have
ReactDOM.render(
<App />,
document.getElementById('app')
);
in there twice. Could be other errors as well, but remove it from App.js and see if that helps.
At first, remove second render in <App />, at second, change var App = require('../components/App'); to import {App} from '../components/App'; And your error must gone.

Deploying react app with webpack server

I am a beginner in ReactJS and was just exploring it and trying to configure it with Webpack and Babel when I experienced an error when I run the application using npm start.
Following are some of files:-
package.json
{
"name": "reactstarter",
"version": "1.0.0",
"description": "A basic React application to explore its state and beauty",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server"
},
"keywords": [
"reactjs"
],
"author": "user1705",
"license": "MIT",
"dependencies": {
"debug-log": "^1.0.1",
"react": "^15.3.2",
"react-dom": "^15.3.2"
},
"devDependencies": {
"webpack": "^1.13.2"
}
}
There are two directories src directory and dist directory inside the root folder.
File: src/index.html
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title>React App</title>
</head>
<body>
<div id = "app"></div>
<script src = "/app/bundle.js"></script>
</body>
</html>
File:- src/app/App.jsx
import React from 'react';
class App extends React.Component {
render() {
return (
<div>
Hello World!!!
</div>
);
}
}
export default App;
File:- src/app/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App />, document.getElementById('app'));
And webpack.config.js:-
var webpack= require(webpack);
var path= require(path);
var DIST_DIR=path.resolve(__dirname,"dist");
var SRC_DIR= path.resolve(__dirname,"src");
var config={
entry:SRC_DIR+"/app/index.js",
output:{
path:DIST_DIR+"/app",
fileName:bundle.js,
publicPath:"/app/",
},
devServer: {
inline: true,
port: 7777
},
modules:{
loaders:[
{
test:/\.js?/,
include:SRC_DIR,
loader:"babel-loader",
query:{
presets:["react","es2015","stage-2"]
}
}
]
}
};
module.exports=config;
So now whenever I run the command npm start,it gives the following error:-
Being a beginner I have no idea as what is the issue?? If anyone has come across this similar issue or knows about the error,please contribute your knowledge and show me the right path.
change
output:{
path:DIST_DIR+"/app",
fileName:bundle.js,
publicPath:"/app/",
},
to
output:{
path:DIST_DIR+"/app",
fileName:"bundle.js",
publicPath:"/app/",
},
It seems that you forgot the quotes when you were requiring the npm modules:
var webpack= require('webpack');
var path= require('path');

After deploying [react-router] "did not match any routes"

I´m currently developing a React-Redux Appliaction using Webpack & npm.
While development I run "start": "node server.js" (from my package.json) and my app is then reachable on localhost:3000/myApp.
But I would like to make this App available to other users. I have a linux server running apache, where some of my previously jQuery Apps are running that work fine.
However, to bundle my React App I run "production": "webpack -p" and the output of this is /dist/bundle.js. Afterwards, I created a html file, included the bundle.js on put both on the server
<!DOCTYPE html>
<html>
<head>
<title>Urlaub-planer</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!--<link rel="stylesheet" href="./Urlaubspalner/css/daterangepicker.css" type="text/css">-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"> </script>
<!-- Auth0Lock script -->
<script src="//cdn.auth0.com/js/lock-9.0.min.js"></script>
</head>
<body>
<div class="todoapp" id="root"></div>
<script src="./bundle.js"></script>
</body>
</html>
When trying to access I got the following error:
browser.js?26d3:49Warning: [react-router] Location "/test/index.html" did not match any routes
This is the File where my Routes are defined
import React from 'react'
import { render } from 'react-dom'
import { createStore, applyMiddleware } from 'redux'
import { Provider } from 'react-redux'
import {Router, Route, IndexRoute, browserHistory} from 'react-router'
import createLogger from 'redux-logger'
import App from './containers/App'
import VacationSummary from './containers/vacation/VacationSummary'
import VacationRequest from './containers/vacation/VacationRequest'
import VacationRequestSummary from './containers/vacation/VacationRequestSummary'
import Home from './containers/Home'
import Demo from './components/Demo'
import rootReducer from './reducers/reducers'
import thunkMiddleware from 'redux-thunk'
var injectTapEventPlugin = require("react-tap-event-plugin");
injectTapEventPlugin();
const logger = createLogger();
let createStoreWithMiddleware = applyMiddleware(thunkMiddleware, logger) (createStore)
let store = createStoreWithMiddleware(rootReducer)
let rootElement = document.getElementById('root')
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('./reducers', () => {
const nextRootReducer = require('./reducers').default
store.replaceReducer(nextRootReducer)
})
}
render(
<Provider store={store}>
<Router history={browserHistory}>
<Route path="/" component={App}>
<Route path="Home" component={Home}/>
<Route path="VacationSummary" component={VacationSummary}/>
<Route path="VacationRequest" component={VacationRequest}/>
<Route path="VacationRequestSummary" component= {VacationRequestSummary}/>
</Route>
</Router>
</Provider>,
rootElement
)
I have found several Questions on SO with a similar purpose, but they are mostly having problems, when running this with the webpack-dev-server.
I want it as I said on my traditional apache server.
What do I have to do, to make this work outside of my development Environment?
Sorry if that Q is to basic, but it is my first project using all this new npm, webpack, node ... stuff and so on.
Finally my package.json
{
"name": "Urlaubsplaner",
"version": "0.0.1",
"main": "index.js",
"scripts": {
"server": "node server/server.js",
"start": "node server.js",
"watch": "webpack --watch",
"production": "webpack -p"
},
"author": "Auth0",
"license": "MIT",
"dependencies": {
"classnames": "^2.2.5",
"css-loader": "^0.23.1",
"material-ui": "^0.15.2",
"moment": "^2.13.0",
"react": "^15.1.0",
"react-bootstrap-daterangepicker": "^3.1.0",
"react-dom": "*",
"react-redux": "*",
"react-router": "*",
"react-tabs": "^0.7.0",
"react-tap-event-plugin": "^1.0.0",
"react-yearly-calendar": "^1.1.4",
"redux": "*",
"redux-form": "^5.2.5",
"redux-logger": "^2.6.1",
"redux-thunk": "*",
"style-loader": "^0.13.1"
},
"devDependencies": {
"babel-core": "^5.6.18",
"babel-loader": "^5.1.4",
"babel-plugin-react-transform": "^1.1.0",
"express": "^4.13.3",
"webpack": "^1.9.11",
"webpack-dev-middleware": "^1.2.0",
"webpack-hot-middleware": "^2.2.0"
}
}
And my webpack.config
var path = require('path')
var webpack = require('webpack')
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: [
'webpack-hot-middleware/client',
'./index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [
{ test: /\.css$/, loader: "style-loader!css-loader" },
{test: /\.js$/,
loaders: [ 'babel' ],
exclude: /node_modules/,
include: __dirname
}]
}
}
Greetings.
According to your current react router paths following links would work:-
/
/VacationSummary
/VacationRequest
/VacationRequestSummary
I cannot find /test/home.html route anywhere in your react-router. So it would throw error for sure. Also you dont need to specific .html in the end for links.
Also I would suggest you to make your /Home Index Route instead of Route.
Now are you localhost:3000/myApp this working, because it should not as myApp is not there in your router urls.
So you home page(or index.html) should be accessible at localhost:3000 from the code you have shared above.

Categories

Resources