react 18 typescript types in package.json - react-18

Im trying to upgrade my react 17 to 18
"#types/react": "???????",
"#types/react-dom": "????????",
"react": "^18.0.0",
"react-dom": "^18.0.0",
What should I put in #types/react and #types/react-dom ?
Thanks

I used Create React App to generate a new TypeScript project and take a look at the dependencies, since I was striking out with the recommendation of removing #types/react and #types/react-dom. That was not fun.
I ended up installing these types:
"#types/react": "^17.0.43",
"#types/react-dom": "^17.0.14",
Then I could use the following to mount my app in index.tsx:
import React from 'react';
import { createRoot } from 'react-dom/client';
....
const container = document.getElementById('root');
// OH BOY, container can be null but createRoot can't handle this...
if (!container) {
throw "Can't instantiate";
}
const root = createRoot(container);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
Yes, there is a problem with the current typescript type where it could receive a null, and you have to guard it with an if / throw check... Or do a ts-ignore.
I'm hoping that gets fixed somehow. But anyway, it's 1AM here and I finally was able to get my app working with React 18 and Typescript using this hack.

At the time I write this, the React 18 types don't appear to be finished yet (see tweet from maintainer). There are former "#next" versions of React 18 types, but they don't match the React 18 release and probably shouldn't be used. Sit tight and they'll likely be finished/released in the coming days.

while react team working on the new types release, if you want to test it out you can keep the old "#types/react": "^17.0.40" and "#types/react-dom": "^17.0.13" types version, and inside the index.tsx after updating react and react-dom to version 18.0.0 you need first to import ReactDOM from react-dom/client and then create the root element from the element id=root using createRoot and then use .render to render the content of the <App/> component inside the created root element like this:
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
let root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>,
);

Looks like #types/react and #types/react-dom are now on v18. Here's how I upgraded:
uninstall both those packages
upgrade to react 18
yarn install -D #types/react #types/react-dom, which automatically uses v18 types now. (or npm install --save-dev ...)
I'm sure there's a way that doesn't require you to uninstall first via yarn upgrade, but that didn't work for me for some reason.

Related

Question regarding NPM, ReactJS, and installed packages both globally, and locally

Question regarding NPM, ReactJS, and installed packages both globally, and locally. I have done quite of bit of searching and found no real resolution. Here's my main App component:
import React, { Component } from 'react'
// import ReactLogger from 'react-terminal-logger/console-logger'
import 'whatwg-fetch'
import Intro from '../Intro/Intro'
import './app.css'
// ReactLogger.config({
// visible: ['log', 'error', 'info', 'warn', 'logr'],
// save_logs: false,
// only_msg: true,
// port: 1234,
// stacktrace_hide: true,
// })
// ReactLogger.start()
class App extends Component {
state = {
series: [],
logs: [],
}
componentDidMount() {
// Hook(window.console, (log) => {
// this.setState(({ logs }) => ({ logs: [...logs, Decode(log)] }))
// })
fetch('http://api.tvmaze.com/search/shows?q=Vikings').then((response) => {
console.log(response)
// logr(response)
})
}
render() {
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">TV Series List</h1>
</header>
<Intro message="Here you can find all you most loved series!" />
The length of the series array is - {this.state.series.length}{' '}
</div>
)
}
}
export default App
Any time I install a package globally, so I can reuse it in other projects I end up with an error when I try to start the server. Such as the logging package (above) react-terminal-logger. I used the following steps:
npm install -g react-terminal-logger
added import and initialized components as per instructions
tried to use component (eg. logr(response))
I end up with the same error at compile time no matter what I installed globally and add to my project.
C:\Users\DawsonSchaffer\Documents\ProjectsDirectory\Projects\reactjsx-tutorial-old\node_modules\react-scripts\scripts\start.js:19
throw err;
[Error: ENOENT: no such file or directory, stat 'C:\Users\DawsonSchaffer\Application Data'] {
errno: -4058,
code: 'ENOENT',
syscall: 'stat',
path: 'C:\\Users\\DawsonSchaffer\\Application Data'
}
My global package prefix points to "C:\Users\DawsonSchaffer\AppData\Roaming\npm" which is the default. If I simply remove the components use by it commenting out everything works.
How do I resolve this? What is the proper way to install a new global package and add it to an existing project? What am I missing? Any help would be greatly appreciated.
One other note, if I install the component locally in my project it works fine. Overall point though is too not have to install it in every project.
Thanks
Dawson
The first thing to understand here is that the global install option of common JS package managers is not intended to facilitate shared project dependencies. To clarify, from NPM itself:
Installing a package globally allows you to use the code in the package as a set of tools on your local computer.
With that out of the way, the optimization you're looking for is a real one, but for different reasons than you may think. When thinking about dependency management, you're really thinking about a small subset of pros and cons related to deciding whether you want use a mono-repo, multi-repo (microservices) or some hybrid.
If you're dealing with entirely different projects that are using the same dependency, then ignore the previous paragraph as they should definitely each manage their own dependencies independently.
Maybe this answer could help you:
How do I install a module globally using npm?
Usually, global installation are meant to be for CLI tools or executable tools.
So I finally got it all straightened out. I uninstalled react, react-dom, and react-scripts from global; leaving me with only create-react-app. I created an empty project called react-boilerplate, and installed react, react-dom, react-scripts, and react-router-dom in the new project. I then uploaded to my GitHub account so I have a common starting point for new projects. Should have thought about this before but it took me a while to wrap my head around everything. Now I can update my boilerplate as needed, and use it to clone as a starting point for new projects. Yeah!
Thanks to everyone especially Dennis G for all his help!!
Dawson

Cant Resolve Installed Npm Module

I uninstalled the package #toast-ui/react-image-editor from the server side of my react app because I thought the dependency needed to be client side, so I go and install it client side, and reboot the app and it cannot be found.
Heres my basic folder structure
-myapp
-server.js
-package.json
-node_modules
-package-lock.json
-client
-package.json
-node_modules
-package-lock.json
-src
I receive this error: "./src/components/images/Editor.js
Module not found: Can't resolve '#toast-ui/react-image-editor' in 'C:..\client\src\components\images'"
Following that I consulted
How do I resolve "Cannot find module" error using Node.js?
Can't resolve module (not found) in React.js
Basically I have deleted and installed the individual package, deleted and installed the node_modules on the client and the server run npm cache verify, installed the package on the client only, installed the package on the client and the server, installed on the server only.
and nothing is working, which makes me think possibly its an import error with VS Code,
is there a way to see how npm is trying to import a specific package or any general thing I haven't done for react failing to import a package that's clearly there.
I got the same error. I think there is a problem with the recent version 3.14.3. I went back to 3.14.2 and it worked fine. Here is my sample App.js to get you started, based on the npm page.
import 'tui-image-editor/dist/tui-image-editor.css';
import ImageEditor from '#toast-ui/react-image-editor';
function App() {
const myTheme = {
// Theme object to extends default dark theme.
};
const MyComponent = () => (
<ImageEditor
includeUI={{
theme: myTheme,
menu: ['shape', 'filter'],
initMenu: 'filter',
uiSize: {
width: '1000px',
height: '700px',
},
menuBarPosition: 'bottom',
}}
cssMaxHeight={500}
cssMaxWidth={700}
selectionStyle={{
cornerSize: 20,
rotatingPointOffset: 70,
}}
usageStatistics={true}
/>
);
return (
<div className="App">
<header className="App-header">
<div><MyComponent /></div>
</header>
</div>
);
}
export default App;

Why does my React Website Take 43 seconds to Load?

I'm not sure why my react website is taking so long to load. It takes 43 seconds
All I have is in index.jsx
import ReactDOM from "react-dom";
import React from "react";
import { HashRouter, Route } from "react-router-dom";
import Home from "./components/Home";
ReactDOM.render(
<HashRouter>
<div>
<Route exact path="/" component={Home} />
</div>
</HashRouter>,
document.getElementById("main")
);
Home.jsx: imports react and renders hi
webpack.config.js : https://pastebin.com/raw/zdUws0R8
package.json : https://pastebin.com/raw/VR6pSP44
index.html : https://pastebin.com/raw/9AVNBpTN
I checked your website and it seems to be working fine to me for now;
For more details, I have added a:
Website Request screenshot
You might want to have a look at your SSL certificate though.
All the best!
I think you need to reinstall your project via :
npx create-react-app YourProject
and use
BrowserRouter
instead of
HashRouter
in 'react-router-dom'
then start the development server after creating the components or editing it via
npm start

Are all packages from package.json included in React build?

I created a react app that both server and client shares the same package.json:
├───build
│ └───static
│ ├───css
│ ├───js
│ └───media
├───server (backend code)
├───src (client code)
├───package.json (shared)
My question is very simple, are all packages from package.json included in the final production React build?
For example, I use express for server. Is it included in the React build?
If so, is there any way to avoid it? Or did I choose a wrong architecture?
Edit:
Im using create-react-app, default mode
No* (in the common case).
The most popular react build tooling will use webpack (or other bundlers which do similar things). Webpack receives some "entry point filepaths", from those entry points he crawls for dependencies. Then webpack packs everything into a single output file (or a set of files, depending on the settings).
If you didn't import express from any of your frontend files, it won't go into the bundle.
Im not sure about combining the package.json for both your express and React app, I dont see an advantage to doing this since React uses webpack and combining the express server might mess up some of the default settings, I will share with you how I do it.
When you are in a development build you will have 2 separate apps running independently. Both the create-react-app and the node/express server will be running independently of each other and they will have their own separate package.json.
In production however you will run npm run build on your React app and it will be served as a static file from your express server. A built React app does not have a package.json
I have implemented both of these scenarios you can check it out here
Dev build:
https://github.com/iqbal125/react_hooks_fullstack_skeleton
Produiction Build:
https://github.com/iqbal125/react-prod9
Previously answered,
According to Webpack doc, Webpack generates a dependency graph starting from entry point which is usually index.js.
And also if you use something like create-react-app that uses webpack under the hood, it will generate a package json like this:
{
"name": "my-app",
"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",
"axios": "^1.3.3",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"build": "react-scripts build",
},
You can see there is no devDependencies! that means not all thing that you just put on the dependencies will be included in your final build.
Finally I've tested inside a new CRA my app:
pressed npm run build on the bare installed:
File sizes after gzip:
46.61 kB build\static\js\main.46f5c8f5.js
1.78 kB build\static\js\787.28cb0dcd.chunk.js
541 B build\static\css\main.073c9b0a.css
Installed axios via npm i axios, but never imported it.
output after running npm run build:
File sizes after gzip:
46.61 kB build\static\js\main.46f5c8f5.js
1.78 kB build\static\js\787.28cb0dcd.chunk.js
541 B build\static\css\main.073c9b0a.css
Nothin has been changed!
import axios from "axios", inside but never use it in the code:
import axios from "axios";
export default function App() {
return (
<div className="App">
</div>
);
}
This is the output:
[eslint]
src\App.js
Line 3:8: 'axios' is defined but never used no-unused-vars
File sizes after gzip:
46.61 kB build\static\js\main.46f5c8f5.js
1.78 kB build\static\js\787.28cb0dcd.chunk.js
541 B build\static\css\main.073c9b0a.css
Again nothing changed! but you can see eslint warning too!
Use one of it's functions e.g. get method only:
import axios from "axios";
export default function App() {
console.log(axios.get);
return (
<div className="App">
</div>
);
}
the output:
File sizes after gzip:
57.92 kB (+11.31 kB) build\static\js\main.4c83ea39.js
1.78 kB build\static\js\787.28cb0dcd.chunk.js
541 B build\static\css\main.073c9b0a.css
Conclusion:
If we don't use a package inside our app, it won't get into the final build.
Note:
Although extra packages won't affect production, don't forget to uninstall unused packages from time to time.
Running npm install still install every package defined in the package.json, no matter whether they are used or not. So having loads of unused packages will slow down deployment and affect your teammates (they need to run npm install as well!!.
Reference

New to React / Babelify; How to fix "Accessing PropTypes" warning

I'm new to both React and Babelify.
I'm using Node to compile a web app. Right now I'm doing this:
browserify({debug: true})
.transform(
babelify.configure({
comments : false,
presets : [
"react",
"babili",
],
})
)
.require('./app.js', {entry: true})
.plugin(collapse)
.bundle()
.on("error", function (err) {
console.log("Error:", err.message);
})
.pipe(fs.createWriteStream(destination));
My app is a VERY trivial "Hello, World!" proof-of-concept at the moment that's about this complex:
class Renderer {
render () {
ReactDOM.render(
<div>Hello, World!</div>
document.querySelector("#react-app")
);
}
}
module.exports = Renderer;
I'm getting this warning:
Warning: Accessing PropTypes via the main React package is deprecated, and
will be removed in React v16.0. Use the latest available v15.* prop-types
package from npm instead. For info on usage, compatibility, migration and more,
see https:/gfb.me/prop-types-docs
Warning: Accessing createClass via the main React package is deprecated,
and will be removed in React v16.0. Use a plain JavaScript class instead. If
you're not yet ready to migrate, create-react-class v15.* is available on npm
as a temporary, drop-in replacement. For more info see
https:/gfb.me/react-create-class
Error: [BABEL] /home/gweb/code/app.js: Unknown option:
/home/gweb/code/node_modules/react/react.js.Children. Check out
http:/gbabeljs.io/docs/usage/options/ for more information about options.
A common cause of this error is the presence of a configuration options
object without the corresponding preset name. Example:
Invalid:
`{ presets: [{option: value}] }`
Valid:
`{ presets: [['presetName', {option: value}]] }`
For more detailed information on preset configuration, please see
http:/gbabeljs.io/docs/plugins/#pluginpresets-options. (While processing
preset: "/home/gweb/code/node_modules/react/react.js") while parsing file:
/home/gweb/code/app.js
I read the recommended stuff, but I'm new enough to both that I can't quite get a handle on it. I also read a bunch of other articles and SO posts, but none of them (that I could find) had this set (browserify, babelify, react).
My goal at the moment is just to get it transpiling with support for the React syntax (which is JSX, from what I understand?), so I can start playing with it and learning both libraries. What's the fastest way to get this implemented (I don't necessarily need most efficient or best; I'd rather have the easiest-to-understand incantation at this stage, so I can have things transparent while I learn).
It is not your setup issue but problem is with your import statements, i'm assuming you are importing react and PropTypes from react
import React, { PropTypes } from 'react';
So, using PropTypes from react library has been deprecated as mentioned in warning and you need to install PropTypes as a standalone library from npm and use that instead.
npm install prop-types --save and then do,
import PropTypes from 'prop-types', for more info https://www.npmjs.com/package/prop-types
this will resolve your first warning, also for second warning you need to install and use https://www.npmjs.com/package/create-react-class.
for the babel error please check if you have both required libraries installed.
https://www.npmjs.com/package/babel-preset-react,
https://www.npmjs.com/package/babel-preset-babili
Do you have an import of the form import * as React from 'react'?
If so, try replacing it with import React from 'react'.
The * imports everything from react, including the deprecated exports, and that's what triggers the warnings.

Resources