Error message with: Web3 + create-react-app + webpack 5 - reactjs

I am writing the frontend for a Dapp.
I have the script /src/config/index.js
import Web3 from 'web3';
const getLibrary = (provider) => {
return new Web3(provider);
};
export { getLibrary };
And the /src/index.js where I am trying to import getLibrary:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { HashRouter } from 'react-router-dom';
import { ChakraProvider } from '#chakra-ui/react';
import { Web3ReactProvider } from '#web3-react/core';
import { getLibrary } from './config/web3';
ReactDOM.render(
<React.StrictMode>
<HashRouter>
<ChakraProvider>
<Web3ReactProvider getLibrary={getLibrary}>
<App />
</Web3ReactProvider>
</ChakraProvider>
</HashRouter>
</React.StrictMode>,
document.getElementById('root')
);
But, I have the error
The line responsible for the error is:
import { getLibrary } from './config/web3';
I used create-react-app to build the project.
I have try several ideas but nothing is working for me... any help, please?

I had the same problem when using web3 with react and webpack 5. This helped me solve it. I followed option #1 as I couldn't get the other option to work (my main confusion being where to keep webpack.config.js since I had kept it at the root and it was not being picked up).

For anyone looking to resolve this still (2022-08-30), I recommend reading this article:
https://alchemy.com/blog/how-to-polyfill-node-core-modules-in-webpack-5
It will be different in regards to your dependencies but it helped resolve my issues. It basically adds support back in by rerouting requests to dependencies using the react-app-rewired package.

Related

Update from reacts-scripts-ts to react--scripts problem

I tried to update from the deprecated library react-scripts-ts to the "new" library react-scripts. I used this link from Vincent Tunru to do that.
But i run then into the Error:
ERROR in ./src/index.tsx 7:0-30
Module not found: Error: Can't resolve './pages/App' in 'C:\develop\remote\src\frontend\src'
I import the App as follow into my start file:
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import App from './pages/App';
import { Provider } from 'react-redux';
import { store } from 'src/store';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root') as HTMLElement);
I have to do a little change to this file as follow './pages/App.tsx' and this error would go away. But then all the files in App also has to be imported as 'file.tsx' and then inside those imported files too. I would have to change over 200 lines. I don't think that this is the correct way to do it. But how should I solve this Error?

ReferenceError: require is not defined when importing ApolloClient from 'apollo-boost'

So I am getting this strange error, ReferenceError: require is not defined when importing ApolloClient from 'apollo-boost'. Without importing ApolloClient app is running but when importing it shows error.
Screenshot of the error is in the image attached:
Here is the image
Here is my Code
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './components/App';
import ApolloClient from 'apollo-boost';
import { ApolloProvider } from 'react-apollo';
const client = new ApolloClient({
uri:"http://localhost:4444/graphql"
})
ReactDOM.render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>
, document.getElementById('root'));
Install graphql v14.0.2 (or new one). Graphql package must be in your package.json.
For more see original solution here: https://github.com/apollographql/apollo-link-state/issues/299#issuecomment-421784547
Go to node_modules/react-scripts/config/webpack.config (both dev && prod files)
{
test: /\.mjs$/,
include: /node_modules/,
type: "javascript/auto"
},
past the above code inside rules: [

#withRouter Unexpected Token Error

Seems every time I have to setup React Router in a new project I run into something new possibly by version changes.
I am using reactjs and mobx state tree(though at this point have not used anything of it).
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import HomeComponent from './HomeComponent.js';
import {withRouter, Route} from 'react-router'
#withRouter
export default class App extends Component {
render() {
return (
<Route exact path='/' component={HomeComponent}/>
);
}
}
export default App;
When I run it I get
ERROR in ./src/components/App.js
Module build failed: SyntaxError /components/App.js: Unexpected token (6:0)
I also get some warning as well
Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning.
Edit
Per the comment from "Artem Mirchenko"
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'mobx-react';
import { useStrict } from 'mobx';
import createBrowserHistory from 'history/createBrowserHistory';
import {syncHistoryWithStore } from 'mobx-react-router';
import { Router } from 'react-router'
import AppContainer from './components/App';
const browserHistory = createBrowserHistory();
import stores from '../src/stores/Stores';
const history = syncHistoryWithStore(browserHistory, stores.routingStore);
ReactDOM.render(
<Provider {... stores}>
<Router history={history}>
<AppContainer />
</Router>
</Provider>,
document.getElementById('app')
);
import {RouterStore} from 'mobx-react-router';
const routingStore = new RouterStore();
const stores = {
routingStore
}
export default stores;
You need to install babel plugin transform-decorators-legacy.
Via yarn:
yard add --dev transform-decorators-legacy
Vie npm:
npm install --save-dev transform-decorators-legacy
And add in to plugins ket in you babel options:
{
// pressets ....
"plugins": ["transform-decorators-legacy"]
}

React relay injectNetworkLayer is not a function

I am following the tutorial from lynda: "Building and Deploying a Full-Stack React Application", in the chapter "Injecting the Relay Network Layer". there is in index.js, an attempt to set up a network layer, and the program compiles successfully but I'm receiving the following error in the browser:
TypeError: __WEBPACK_IMPORTED_MODULE_4_react_relay___default.a.injectNetworkLayer is not a function
index.js file is:
import React from 'react'
import ReactDOM from 'react-dom'
import {Router, browserHistory, applyRouterMiddleware} from 'react-router'
import Routes from './routes'
import Relay from 'react-relay'
import useRelay from 'react-router-relay'
import {RelayNetworkLayer, urlMiddleware} from 'react-relay-network-layer'
import {relayApi} from './config/endpoints'
import auth from './utils/auth'
const createHeaders = () => {
let idToken = auth.getToken()
if (idToken) {
return {
'Authorization': `Bearer ${idToken}`
}
} else {
return {}
}
}
Relay.injectNetworkLayer(
new RelayNetworkLayer([
urlMiddleware({url: (req) => relayApi,}),
next => req => {
req.headers = {
...req.headers,
...createHeaders()
}
return next(req)
},
],{disableBatchQuery: true})
)
ReactDOM.render(
<Router
environment={Relay.Store}
render={applyRouterMiddleware(useRelay)}
history={browserHistory}
routes={Routes}
/>,
document.getElementById('root')
)
It might be easier to just use the classic version of react-relay.
import Relay from 'react-relay/classic'
Duplicate question.
Found Chris Mazzouchi's answer helpful, though I had to uninstall and re-install the following specific versions to get it working:
yarn remove react-relay react-relay-network-layer react-router-relay
yarn add react-relay#0.10.0 react-relay-network-layer#1.3.9 react-router-relay#0.13.5

Upgrading React-Router and replacing hashHistory with browserHistory

I have a bootstrap+react theme that was using react-router 1.x and hashHistory and I wanted to remove the hash so followed this advice.
Initially I tried to do this while having the 1.x version and I was unable to do it so I've decided to upgrade react-router to 2.x.
After installing react-router 2.x the app worked because it was still using hashHistory but when I replaced it with browserHistory:
it showed a grey screen
the HTML of the app had only the <noscript data-reactid=".0"></noscript> tag inside it
the React Developer Tools showed me that the router had a null inside it
I also checked the Network tab and all files were downloaded properly, and had the right content
surprisingly the was nothing printed in the JavaScript Console, no error/no warnging (I'm really shocked about this, but I'm new React, I would like to know what to do in situations like this).
Here are my changes to Router.jsx:
import React from 'react'
import {render} from 'react-dom'
-import {Router} from 'react-router'
+// import {Router} from 'react-router'
+import { Router, Route, Link, browserHistory } from 'react-router'
+// import { useRouterHistory } from 'react-router'
+// import { createHashHistory } from 'history'
+// import { createBrowserHistory } from 'history'`
import History from '../components/layout/navigation/classes/History.js';
import Routes from './Routes.jsx';
+// const appHistory = useRouterHistory(createHashHistory)({ queryKey: false })
+
var rootInstance = render((
- <Router history={History}>
+ <Router history={browserHistory}>
{Routes}
</Router>
), document.getElementById('smartadmin-root'));`
The backend uses the Phoenix Framework.
Later Edit:
Here you have the hashHistory version that works
https://gitlab.com/blockbuster/react-router-2-with-hash-working/tree/master
And here is the browserHistory version that doesn't:
https://gitlab.com/blockbuster/react-router-2-with-browserHistory-not-working/tree/master
The react code for both can be found under the src directory.
To run the app you need to have Elixir, Phoenix and Postgresql installed, to get backend dependencies( run $ mix deps.get), get frontend dependecies( npm install and bower install), to change the database username and password in config/dev.exs, to create and migrate the database mix ecto.create && mix ecto.migrate and finally run mix phoenix.server.
Have you tried it this way in your Router.jsx?
import React from 'react'
import {render} from 'react-dom'
import { Router, Route, Link, browserHistory, useRouterHistory } from 'react-router'
import createBrowserHistory from 'history/lib/createBrowserHistory'
import History from '../components/layout/navigation/classes/History.js';
import Routes from './Routes.jsx';
const appHistory = useRouterHistory(createBrowserHistory)({ queryKey: false })
var rootInstance = render((
<Router history={appHistory}>
{Routes}
</Router>
), document.getElementById('smartadmin-root'));
Since there is no solution yet, find my (minimalistic) router version below, that is working for me.
Dependencies:
react#15.1.0
react-dom#15.1.0
react-router#2.4.0
History.js is not needed explicitly, since it is a dependency of react-router.
Webpack
Make sure to add
devServer: {
historyApiFallback: true
}
to your webpack.config.js, since webpack-dev-server might have some issues routing correctly (mostly in terms of backwards navigation).
import React from 'react';
import {render} from 'react-dom';
import {Router, Route, IndexRoute, browserHistory} from 'react-router';
import {Routes} from './Routes'; // your routes file
render(
<Router history={browserHistory}>
{Routes}
</Router>,
document.querySelector('#smartadmin-root')
);
I would encourage you to try this code and leave out your hotloading stuff.
Let me know if it helps and if there are any questions. I'm glad to edit my post as needed.

Resources