问题
I'm trying to run my first React JSX file with create-react-app with version 4.0.0 and it works! However, I don't have the import statements of React included in my JSX and it works too but it is very weird. The project is created by create-react-app command with version 4.0.0.
The App.js file:
/* without import React but works too! */
import { Component } from "react";
class App extends Component {
render() {
return <div>456</div>;
}
}
export default App;
回答1:
This is new with the JSX transform introduced with React 17
:
Together with the React 17 release, we’ve wanted to make a few improvements to the JSX transform, but we didn’t want to break existing setups. This is why we worked with Babel to offer a new, rewritten version of the JSX transform for people who would like to upgrade.
Upgrading to the new transform is completely optional, but it has a few benefits:
- With the new transform, you can use JSX without importing React.
- Depending on your setup, its compiled output may slightly improve the bundle size.
- It will enable future improvements that reduce the number of concepts you need to learn React.
回答2:
Starting from React 17 it's not necessary to import React to use JSX. See from the blog post about that in the section called Removing Unused React Imports:
Because the new JSX transform will automatically import the necessary react/jsx-runtime functions, React will no longer need to be in scope when you use JSX. This might lead to unused React imports in your code.
What’s a JSX Transform?
Browsers don’t understand JSX out of the box, so most React users rely on a compiler like Babel or TypeScript to transform JSX code into regular JavaScript.
Suggested read is Introducing the New JSX Transform. Also you can see Using React 17 and the new JSX transform with Create React App 4.0 Alpha.
来源:https://stackoverflow.com/questions/64541040/jsx-can-be-used-without-importing-react