In the previous post we did setup the Development environment to
develop React applications using TypeScript. In this post we will use this environment
and create a Hello World React application using TypeScript.
Assuming we have a root folder and the environment setup with required npm packages installed and config files we will go ahead and create the Application files. First let us create the following folder structure for the React components.
Assuming we have a root folder and the environment setup with required npm packages installed and config files we will go ahead and create the Application files. First let us create the following folder structure for the React components.
./src
./src/components
Next let us create a basic Hello World React application using TypeScript as follows. The file name will be App.tsx and will be in the /src/components folder
import * as React from "react";
export class App extends React.Component {
render() {
return
<h3>Hello World</h3>;
}
}
Next let us create a file index.tsx in the /src folder, this file will contain ReactDOM.render and will bootstrap the App component. We can combine both these into a single file, but we will maintain it as separate files.
import * as React from "react";
Next let us create a file index.tsx in the /src folder, this file will contain ReactDOM.render and will bootstrap the App component. We can combine both these into a single file, but we will maintain it as separate files.
import * as React from "react";
import * as ReactDOM from "react-dom";
import { App } from "./components/App";
ReactDOM.render(
<App />,
document.getElementById("root")
);
Next we will create the HTML file index.html which will host the React Application, this file will be in the root folder.
<html>
Next we will create the HTML file index.html which will host the React Application, this file will be in the root folder.
<html>
<head>
<title>Hello React TypeScript</title>
</head>
<body>
<div
id="root"></div>
<script
src="./node_modules/react/umd/react.development.js"></script>
<script
src="./node_modules/react-dom/umd/react-dom.development.js"></script>
<script
src="./dist/main.js"></script>
</body>
</html>Now we have created all the files needed for the react Application, now we need to build the Application, which will compile the TypeScript files and convert them into JavaScript which the browser can understand. Webpack will use TypeScript loader to do this conversion.
Notice that the index.html file is referencing to ./dist/main.js file, this file is the output of the build process. Run the following command to build the project, this will create the main.js file.
npx webpack
Now the main.js file should be created in the ./dist folder, open the index.html file in the root folder in a browser and the output will be as follows.
No comments:
Post a Comment