React syntax
The React project uses the JSX and Class syntax. For example:
class Button extends Component {
render() {
return <h1>Hello,Webpack</h1>}}Copy the code
The JSX syntax does not run in any existing JavaScript engine, so the source code needs to be converted into runnable code during the build process, for example:
// Original JSX syntax code
return <h1>Hello,Webpack</h1>
// Is converted to normal JavaScript code
return React.createElement('h1'.null.'Hello,Webpack')
Copy the code
The React with Babel
Run the following command:
Install the React base dependency
npm i -D react react-dom
Install Babel to complete syntax conversion
npm i -D babel-preset-react
Copy the code
After installing the new dependencies, modify the.babelrc configuration file to add the React Presets
"presets": [
"react"].Copy the code
Then modify the main.js file as follows:
import * as React from 'react';
import { Component } from 'react';
import { render } from 'react-dom';
class Button extends Component {
render() {
return <h1>Hello,Webpack</h1>
}
}
render(<Button/>.window.document.getElementById('app'));
Copy the code
Re-execute the build and open the page. You’ll find Hello,Webpack rendered by React
React with the TypeScript
TypeScript’s advantage over Babel is that it supports JSX syntax nave, so you don’t have to reinstall new dependencies, just change one line of configuration. But TypeScript is different in that:
- The file suffix that uses JSX syntax must be
tsx
. - Because React is not written in TypeScript, it needs to be installed
react
和react-dom
The corresponding TypeScript interface describes the module@types/react
和@types/react-dom
Before it can be compiled.
Modify the TypeScript compiler configuration file tsconfig.json to add support for JSX syntax as follows:
{
"compilerOptions": {
"jsx": "react" // Enable JSX and React}}Copy the code
JSX syntax exists in the main.js file, rename the main.js file to main. TSX, and change the contents of the file to the React code used in the React and Babel files above. In order for Webpack to convert ts and TSX files using awesome-typescript-loader, it should be noted that the test option configured by Webpack Loader should match TSX files. You should also add.tsx to extensions as follows:
const path = require('path');
module.exports = {
// TS executes the entry file
entry: './main'.output: {
filename: 'bundle.js'.path: path.resolve(__dirname, './dist'),},resolve: {
// Try the ts, TSX TypeScript source files first
extensions: ['.ts'.'.tsx'.'.js',]},module: {
rules: [{// Also matches the ts, TSX, TypeScript source files
test: /\.tsx? $/,
loader: 'awesome-typescript-loader'}},devtool: 'source-map'.// Output Source Map to debug TypeScript code in the browser
};
Copy the code
npm i react react-dom @types/react @types/react-dom
Copy the code
Install the new dependency, restart the build, reopen the page and you’ll find Hello,Webpack rendered by React