Getting compilation errors regarding loaders when running React app - javascript

Hi I'm having an issue when trying to run my react app. I've installed a couple of packages to from a tutorial using the ceramic and 3id networks. This error has only shown up recently and I've looked online but still not too sure what be causing the issue. The version of node I am using is v14.15.0, my npm version is 6.14.8 and I'm on Windows 11 home version 21H2
The error in question is:
Failed to compile.
./node_modules/did-jwt/lib/index.module.js 1684:17
Module parse failed: Unexpected token (1684:17)
File was processed with these loaders:
* ./node_modules/react-scripts/node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| // TODO: should be able to use non base58 keys too
| return key.type === 'X25519KeyAgreementKey2019' && Boolean(key.publicKeyBase58);
> })) ?? [];
| if (!pks.length && !controllerEncrypters.length) throw new Error(`no_suitable_keys: Could not find x25519 key for ${did}`);
| return pks.map(pk => x25519Encrypter(base58ToBytes(pk.publicKeyBase58), pk.id)).concat(...controllerEncrypters);
My package.json file is as follows:
{
"name": "ceramic-test",
"version": "0.1.0",
"private": true,
"dependencies": {
"#3id/connect": "^0.2.5",
"#ceramicnetwork/3id-did-resolver": "^1.4.8",
"#ceramicnetwork/http-client": "^1.4.4",
"#ceramicstudio/idx": "^0.12.2",
"#testing-library/jest-dom": "^5.11.4",
"#testing-library/react": "^11.1.0",
"#testing-library/user-event": "^12.1.10",
"dids": "^2.4.0",
"ethers": "^5.5.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "4.0.3",
"web-vitals": "^1.0.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
The current code I have is also just this in my App.js
import './App.css';
import {useState} from 'react';
import CeramicClient from '#ceramicnetwork/http-client'
import ThreeIdResolver from '#ceramicnetwork/3id-did-resolver'
import { EthereumAuthProvider, ThreeIdConnect } from '#3id/connect'
import { DID } from 'dids'
import { IDX } from '#ceramicstudio/idx'
const endpoint = "https://ceramic-clay.3boxlabs.com"
function App() {
const [name, setName] = useState('');
const [image, setImage] = useState('');
const [loaded, setLoaded] = useState(false);
async function connect() {
const addresses = await window.etheruem.request({
method: 'eth_requestAccounts'
})
return addresses;
}
async function readProfile() {
const [address] = await connect();
const ceramic = new CeramicClient(endpoint);
const idx = new IDX({ceramic});
try {
const data = await idx.get(
'basicProfile',
`${address}#eip155:1`
);
console.log('data: ',data);
if (data.name) {
setName(data.name);
}
if (data.avatar) {
setImage(data.avatar);
}
} catch (e) {
console.error('error: ',e);
setLoaded(true);
}
}
return (
<div className="App">
<button onClick={readProfile}>Read Profile</button>
</div>
);
}
export default App;

Update 2021-12-23
This issue is fixed in Create React App version 5.
Create React App does not currently support some features of ES2020 (Modern Javascript) in imported modules.
?? is the ES2020 Nullish coalescing operator and use of this in the imported Ceramic module causes the build to fail.
The issue is discussed here and seems unlikely to be fixed until the next major version of Create React App.
Two options are to use an alternative React framework such as Next.js which supports the features (example/instructions here), or to set up the React project manually.
Other possible solutions are discussed in this stack overflow question, but the accepted answer will not work when the issue occurs in an imported library.

Related

When I add progress bar it throws Module not found: Error: Can't resolve in React

I'm new on React and I'm stuck on something. I added a new component as a 'react-customizable-progressbar' in my project. I have the following files in yellow. These were the ones that I created.
The problem point to
ERROR in ./src/example1.js 6:0-73
Module not found: Error: Can't resolve './CircularProgressBarContainer' in 'C:\Alex Maricoiu\Projects\React projects\project1\src'
Failed to compile.
CircularProgressBarContainer.tsx have the following code:
import React, {FunctionComponent} from "react";
import ICustomIndicatorProperties from './IProgressBarProperties';
import ProgressBar from 'react-customizable-progressbar'
const CustomProgressIndicator : FunctionComponent<ICustomIndicatorProperties> = ({value, title}) => {
return (
<div className="text-and-value" style={{width: "29em"}}>
<div className="title-text">{title}</div>
<div className="custom-progress-bar">
<ProgressBar
radius={100}
progress={value}
strokeWidth={18}
strokeColor="#5d9cec"
strokeLinecap="square"
trackStrokeWidth={18}
>
<div className="indicator">
<div>{value}%</div>
</div>
</ProgressBar>
</div>
</div>
)
};
export default CustomProgressIndicator;
Example1.js:
import {useState} from 'react';
import {CustomProgressIndicator} from './CircularProgressBarContainer';
function Button(props) {
return (
<button onClick={props.onClickFunc}>
Increment by 1
</button>
);
}
function Display(props){
// eslint-disable-next-line no-undef
const [counter, setCounter] = useState(0);
const incrementValue = () => setCounter(counter+1);
return (
<div>
<Button onClickFunc={incrementValue}/>
<b> Current value is: {counter}</b>
<CustomProgressIndicator
value={counter}
title ='Indicator Exercise 1'
/>
</div>
)
}
function App(props){
return (
<div>
<Display />
</div>
)
}
export default App;
The Interface file has (IProgressBarProperties.tsx):
interface ICustomIndicatorProperties {
title: string;
value: number;
}
export default ICustomIndicatorProperties;
And Main.js:
import './Main.css';
import Example1 from './example1';
import { Component } from 'react';
class App extends Component {
render(){
return (
<>
<div className='header'>Alex React Examples</div><div className='content'>
<h3>Example #1</h3>
<div id='example1Node'>
<Example1 />
</div>
</div>
</>
);
}
}
export default App;
Index.js:
import React from 'react';
import ReactDOM from 'react-dom/client';
import MainApp from './Main';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<MainApp />
</React.StrictMode>
);
package.json:
{
"name": "project1",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"#testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-customizable-progressbar": "^1.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
I use Node.js 19.3.0.
I tried to find from the browser console what is the problem, but I was stuck.
I tried to remove the node_modules and run this command again in terminal: npm install.
If I remove the reference to the file where is the progress bar the app is working, but with that failed with the error mentioned. Is there any way to find a solution to that error?
Thank you in advance
I use Node.js 19.3.0.
I tried to find from the browser console what is the problem, but I was stuck.
I tried to remove the node_modules and run this command again in terminal: npm install.
If I remove the reference to the file where is the progress bar the app is working, but with that failed with the error mentioned. Is there any way to find a solution to that error?
Try replacing import {CustomProgressIndicator} from './CircularProgressBarContainer'; with import CustomProgressIndicator from './CircularProgressBarContainer';, since you are using export default. Curly braces are used for normal (non-default) export. Alternatively remove default from export default.
UPDATE/RESOLVE
I came back with a solution. After I investigate a little seems that there was a incorrect path to the local module created (to the local TSX file).
The UPDATE was in Example1.js. When I put the path, intellisense show me the correct way to import and I hit Enter in order to complete the path. Fine for this. The import looked like this
import {CustomProgressIndicator} from './CircularProgressBarContainer';
The problem was just right here. I correct like it is bellow and it worked.
import {CustomProgressIndicator} from './CircularProgressBarContainer.tsx';
The final result is this. The component marked in yellow was the problem.
Thank you everyone.

I can't use the apploading on my react native. It wont work properly

I keep getting this error: error screenshot
Here is the code that im using to import my custom google fonts:
import React, { useState } from "react";
import Home from "./screens/home";
import { View } from "react-native";
import * as Font from "expo-font";
import { AppLoading } from "expo";
const getFonts = () =>
Font.loadAsync({
"poppins-regular": require("./assets/fonts/Poppins-Regular.ttf"),
"poppins-bold": require("./assets/fonts/Poppins-Bold.ttf"),
});
export default function App() {
const [fontsLoaded, setFontsLoaded] = useState(false);
if (fontsLoaded) {
return <Home />;
} else {
return (
<AppLoading startAsync={getFonts} onFinish={() => setFontsLoaded(true)} />
);
}
}
Here is my Json Package:
{
"main": "node_modules/expo/AppEntry.js",
"scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web",
"eject": "expo eject"
},
"dependencies": {
"expo": "~40.0.0",
"expo-splash-screen": "^0.8.1",
"expo-status-bar": "~1.0.3",
"react": "16.13.1",
"react-dom": "16.13.1",
"react-native": "https://github.com/expo/react-native/archive/sdk-40.0.1.tar.gz",
"react-native-web": "~0.13.12"
},
"devDependencies": {
"#babel/core": "~7.9.0"
},
"private": true
}
I can't seem to find the error or fix it. I did this with another project before and it worked. The getting the font info is exactly the same. The only thing i can think of is maybe my packages are outdated atm? but Im not sure which package to even update.
Can someone please help?
I can see from your package.json that you are at expo SDK 40 (latest release as of now)
AppLoading has been extracted from the expo package in SDK 40
If you want to use this component, you should run expo install expo-app-loading and import AppLoading from its own package: import AppLoading from 'expo-app-loading';. This is part of an ongoing effort to make the expo package as lightweight as possible.
Check the expo blog here.
Steps:
STEP 1: expo install expo-app-loading
STEP 2:
replace import { AppLoading } from "expo";
by import AppLoading from 'expo-app-loading';
STEP 3: Restart your expo dev server (expo start)
My problem was that the first time reloading the app (with expo), the fonts were not loading.
After deleting, rewriting and saving the fontFamily inside of my StyleSheet, the text was being styled with the right font, as the app updates automatically every time you save a file.
I just couldn't make it work at the first load.
I solved the issue by putting a return in front of the Font.loadAsync() function:
const fetchFonts = () => {
return Font.loadAsync({ // <- add return here
"open-sans": require("./assets/fonts/OpenSans-Regular.ttf"),
"open-sans-bold": require("./assets/fonts/OpenSans-Bold.ttf"),
});
};
Now the AppLoading's startAsync gets the promise correctly and the fonts are loaded right after loading the app, without errors
const [isDataLoaded, setIsDataLoaded] = useState(false);
if (!isDataLoaded) {
return (
<AppLoading
startAsync={fetchFonts}
onFinish={() => setIsDataLoaded(true)}
onError={(err) => console.log(err)}
/>
);
}
you have to add the return keyword infront of font.loadAsync
Just a heads up, as of today, using startAsync method is depracted in expo-app-loading, you can use useEffect instead and run your function as you would like and handle all the errors there,
useEffect(() => {
const getAsyncData = async () => {
// Do my async request
setIsReady(true);
}
getAsyncData ();
}, [])
Assuming you have something like const [isReady, setIsReady] = useState(false); in your code
for me the following steps result:
STEP 1: stop device
STEP 2: expo install expo-app-loading
STEP 3: add the next line: import AppLoading from 'expo-app-loading';
STEP 4:
if (!isDataLoaded) {
return (
<AppLoading
    startAsync={fetchFonts}
    onFinish={() => setIsDataLoaded(true)}
    onError={(err) => console.log(err)}
    />
  );
}

Using any form of the Map function with react causes an undefined error

After reducing my code to the simplest of forms it looks like I have an un-resolvable problem with the map function used anywhere in any location.
I know code in examples which runs on Codepen etc doesn't work with create react app project locally, so I'm wondering if there is an issue with the build setup.
I'm new to react, and haven't been actively programming for about 4-5 years, so its very possible I am at fault
Error is the iterator parameter within the map having an undefined value: 'd' below in this and the days worth of writing similar code to find a solution
The code is as follows after reducing it to its simplest form
Code which doesn't work in my build works on codepen.
I've tried props, state class or block variables
I've tried nested functions, as well as => functions
I've tried with different classes different variables, and the error is always exactly the same
import { React, Component } from 'react';
class ProtoList extends Component {
constructor(props) {
super(props)
this.state = {
};
}
render() {
let data = [{ "name": "test1" }, { "name": "test2" }];
let listItems = data.map(d =>
<span key={d.name}>{d.name}</span>
)
return listItems;
}}
export default ProtoList;
import React from 'react';
import Container from '#material-ui/core/Container';
import { makeStyles } from '#material-ui/core/styles';
import WebHeader from './components/WebHeader';
import WebMain from './components/WebMain';
import WebFooter from './components/WebFooter';
import ProtoList from './components/ProtoList';
const useStyles = makeStyles(theme => ({
root: {
minHeight: '500px',
paddingLeft: '0px',
paddingRight: '0px',
backgroundColor: '#001e1c',
},
}));
export default function App() {
const classes = useStyles();
return (
<ProtoList />
/*
<Container className={classes.root}>
<WebHeader />
<WebMain />
<WebFooter />
</Container>
*/
);
}
Package:
{
"name": "telescout-pr2",
"version": "0.1.0",
"private": true,
"dependencies": {
"#fortawesome/fontawesome-svg-core": "^1.2.22",
"#fortawesome/free-brands-svg-icons": "^5.10.2",
"#fortawesome/react-fontawesome": "^0.1.4",
"#material-ui/core": "^4.3.3",
"#material-ui/icons": "^4.2.1",
"react": "^16.9.0",
"react-dom": "^16.9.0",
"react-scripts": "3.1.1",
"react-vis": "^1.11.7",
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"eslint": "^6.2.2",
"eslint-plugin-react": "^7.14.3"
}
}
TypeError: Cannot read property 'createElement' of undefined
(anonymous function)
render() {
let data = [{ "name": "test1" }, { "name": "test2" }];
> let listItems = data.map(d =>
<span key={d.name}>{d.name}</span>
)
return listItems;
The createElement method is the primary method React uses to build components, it's undefined because the React object isn't being imported:
import React, { Component } from 'react';
Cheers!
Try this
render() {
let data = [{ "name": "test1" }, { "name": "test2" }];
return (
<>
{data.map(d => <span key={d.name}>{d.name}</span>}
</>
);
}}
If you are returning an array of elements, they must be wrapped in a JSX element.
Also, just a tip on React. If you aren't using state, make it a functional component, not a class component.

How can I use a React component within a Node script?

I'm currently trying to use react-pdf to generate and save a pdf to disk. Rendering to a webpage works, but the method that I need to invoke to save a pdf to disc,
ReactPDF.render()
does not work within the npm start (react-scripts) way of running React that I've used in the past to create webpages. From reading this issue, it seems that it needs to be run as a "Node only api". So my question is, what dependencies, commands, and steps do I need to take to run some react code and save a pdf to disk with something like
> node index.js
currently when I run the above command I get
import React from 'react';
^^^^^
SyntaxError: Unexpected identifier
Then, running
node --experimental-modules index.mjs
I get
ReactPDF.render(<App />, `${__dirname}/output/test.pdf`);
^
SyntaxError: Unexpected token <
Here are my two files:
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import ReactPDF from '#react-pdf/renderer';
ReactPDF.render(<App />, `${__dirname}/output/test.pdf`);
//ReactDOM.render(<App />, document.getElementById('root'));
App.js
import React, { Component } from 'react';
import { Document, Page, Text, View, StyleSheet } from '#react-pdf/renderer'
class App extends Component {
render() {
const styles = StyleSheet.create({
page: {
flexDirection: 'row',
backgroundColor: '#E4E4E4'
},
section: {
margin: 10,
padding: 10,
flexGrow: 1
}
});
return (
<Document>
<Page size="A4" style={styles.page}>
<View style={styles.section}>
<Text>Section #1</Text>
</View>
<View style={styles.section}>
<Text>Section #2</Text>
</View>
</Page>
</Document>
);
}
}
export default App;
package.json
{
"name": "ccv-generator-react",
"version": "0.1.0",
"private": true,
"dependencies": {
"#react-pdf/renderer": "^1.4.2",
"react": "^16.8.5",
"react-dom": "^16.8.5",
"react-scripts": "2.1.8",
"ts-pnp": "^1.0.1",
"typescript": "^3.3.4000"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
],
"devDependencies": {
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1"
}
}
A follow up question would be, Is what I am trying to do an anti-pattern?
Since you're running index.mjs directly from node, it does not go through the build and transpilation process of react-scripts, meaning you have to do it manually.
Node cannot directly parse jsx (<App/>, for example) - so you will need to run your code through Babel with React preset in order to run it.
Since the dependecies should be already installed, try running:
npx babel index.mjs -o index-compiled.js --presets=es2015,react
and then run the compiled file:
node index-compiled.js

Why am I getting "TypeError: react__WEBPACK_IMPORTED_MODULE_1___default.a.useState is not a function" error when using reactjs hooks?

I'm trying to use this component straight from the Material Ui (Simple Menu https://material-ui.com/demos/menus/#menus) docs in order to make a menu appear. However, I'm getting TypeError: react__WEBPACK_IMPORTED_MODULE_1___default.a.useState is not a function error with my current attempt below. I tried:
import React, { useState } from 'react'; and then got rid of React inside const [anchorEl, setAnchorEl] = React.useState(null); to make it look like: const [anchorEl, setAnchorEl] = useState(null);
I also tried replacing null with a number but still got same error.
Note: Another attempt installed the right packages and made my package.json file look like this (TypeError dispatcher.useState is not a function when using React Hooks):
{
"name": "speedy-react",
"version": "0.1.0",
"private": true,
"dependencies": {
"#material-ui/core": "^3.9.0",
"#material-ui/icons": "^3.0.2",
"classnames": "^2.2.6",
"node-sass": "^4.11.0",
"prop-types": "^15.6.2",
"react": "16.7.0-alpha.0",
"react-dom": "16.7.0-alpha.0",
"react-test-renderer": "16.7.0-alpha.0",
"react-scripts": "2.1.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
]
}
Screen shot of error:
What am I doing wrong and how can I fix it?
import React from 'react';
import Button from '#material-ui/core/Button';
import Menu from '#material-ui/core/Menu';
import MenuItem from '#material-ui/core/MenuItem';
const SimpleMenu = () => {
const [anchorEl, setAnchorEl] = React.useState(null);
function handleClick(event) {
setAnchorEl(event.currentTarget);
}
function handleClose() {
setAnchorEl(null);
}
return (
<div>
<Button
aria-owns={anchorEl ? 'simple-menu' : undefined}
aria-haspopup="true"
onClick={handleClick}
>
Open Menu
</Button>
<Menu id="simple-menu" anchorEl={anchorEl} open={Boolean(anchorEl)} onClose={handleClose}>
<MenuItem onClick={handleClose}>Profile</MenuItem>
<MenuItem onClick={handleClose}>My account</MenuItem>
<MenuItem onClick={handleClose}>Logout</MenuItem>
</Menu>
</div>
);
};
export default SimpleMenu;
While I'm not sure what is wrong in the code above (my guess is using a non-release build of material-ui in which an export was not default as it documentation states), this error occurred for me with improper imports. My issue was that I was trying to
import someNonDefaultFunction from 'someModule';
Adding the braces around the named/non-default import resolved the same error message for me:
import {someNonDefaultFunction} from 'someModule';

Categories

Resources