Skip to content

Create a basic web application with React, Typescript, and webpack

liyuanqian edited this page Jul 14, 2023 · 1 revision

This tutorial explains how to create a basic React web application. To provide an enhanced development experience and tooling, the project is configured to use TypeScript for type safety and webpack for building and bundling the application code.

Note: This tutorial requires that you use one of the following operating systems: cloud9, OS and Linux.

Prerequisites

Before you begin, verify that you have the following prerequisites:

  1. You have downloaded Node.js 16+. npm recommends using a Node version manager, e.g. nvm to install Node.js and npm.
  2. npm 8+ is installed on your machine. npm is automatically installed when you install Node.js or a Node.js version manager.
  3. An IDE or code editor of your choice, for example AWS Cloud9 or Visual Studio Code.

Steps

Section 1: Establish a project and its install dependencies

Section 2: Create project files and content

Section 3: Build and run the application

Section 1: Establish a project and install its dependencies

This topic will show you how to setup the required project files and install the dependencies.

Create the project directory

mkdir myapp && cd myapp

Initialize the project package

For more information about npm or how to use it, visit the npm documentation site.

npm init -y

Install the development dependencies

npm install -D \
  @babel/core @babel/preset-env @babel/preset-react @babel/preset-typescript \
  webpack webpack-cli webpack-dev-server \
  babel-loader css-loader style-loader \
  html-webpack-plugin mini-css-extract-plugin \
  sass sass-loader \
  typescript \
  path \
  @types/react-dom

Install the runtime dependencies

npm install -S react react-dom

After completing this section, your project structure should be:

+ myapp
+ |- node_modules/
+ |- package-lock.json
+ |- packge.json

Section 2: Create project files and content

After completing this section, your project structure should be:

  myapp
  |- node_modules/
+ |- src/
+   |- index.tsx
+ |- index.html
  |- package-lock.json
  |- packge.json
+ |- tsconfig.json
+ |- webpack.config.js

Create the TypeScript configuration file

Create the file.

touch tsconfig.json

Open tsconfig.json, paste the following configuration code, and save.

For more information about TypeScript, its configuration, or how to use it, visit the TypeScript documentation site.

{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "lib": ["DOM", "DOM.Iterable", "ESNext"],
    "allowJs": false,
    "skipLibCheck": true,
    "esModuleInterop": false,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "verbatimModuleSyntax": true,
    "module": "ESNext",
    "moduleResolution": "Node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": false,
    "jsx": "react-jsx",
    "baseUrl": ".",
    "outDir": "./dist/"
  },
  "include": ["src"],
  "exclude": ["node_modules"]
}

Create the webpack configuration file

Create the file.

touch webpack.config.js

Open webpack.config.js, paste the following configuration code, and save.

For more information about webpack, its configuration, or how to use it, visit the webpack documentation site.

import HtmlWebpackPlugin from 'html-webpack-plugin';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

export default {
  devServer: {
    https: true,
    hot: true,
    port: 8080,
    static: './public/',
  },

  devtool: 'inline-source-map',
  entry: './src/index.tsx',
  mode: 'development',

  module: {
    rules: [
      {
        test: /\.(ts|js)x?$/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [
              '@babel/preset-env',
              ['@babel/preset-react', { runtime: 'automatic' }],
              '@babel/preset-typescript',
            ],
          },
        },
        exclude: /node_modules/,
      },
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.s[ac]ss$/i,
        use: ['style-loader', 'css-loader', 'sass-loader'],
      },
    ],
  },

  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, '/dev/'),
  },

  plugins: [
    new HtmlWebpackPlugin({ template: './index.html' }),
    new MiniCssExtractPlugin({ filename: '[name].css', chunkFilename: '[name].css' }),
  ],

  resolve: {
    extensions: ['.tsx', '.ts', '.js', '.css', '.scss'],
  },
};

Edit the package file

Open package.json, add the following properties, and save.

{
  ...
  "scripts": {
    ...
    "dev": "webpack serve --config webpack.config.js"
  }
  ...
  "type": "module"
}

At this point, your package.json should be similar to following example (package versions may vary).

{
  "name": "myapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack serve --config webpack.config.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.22.8",
    "@babel/preset-env": "^7.22.7",
    "@babel/preset-react": "^7.22.5",
    "@babel/preset-typescript": "^7.22.5",
    "@types/react-dom": "^18.2.6",
    "babel-loader": "^9.1.2",
    "css-loader": "^6.8.1",
    "html-webpack-plugin": "^5.5.3",
    "mini-css-extract-plugin": "^2.7.6",
    "path": "^0.12.7",
    "sass": "^1.63.6",
    "sass-loader": "^13.3.2",
    "style-loader": "^3.3.3",
    "typescript": "^5.1.6",
    "webpack": "^5.88.1",
    "webpack-cli": "^5.1.4",
    "webpack-dev-server": "^4.15.1"
  },
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "type": "module"
}

Create the HTML template file

Create the file.

touch index.html

Open index.html, paste the following HTML code, and save.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>My Application</title>
  </head>
  <body>
    <main id="app"></main>
  </body>
</html>

Create the application source directory

mkdir src

Create the application entry-point file

Create the file.

touch src/index.tsx

Open index.tsx, paste the following React code, and save.

import { createRoot } from 'react-dom/client';

const element = document.getElementById('app');

if (element) {
  createRoot(element).render('Hello world!');
}

Section 3: Build and run the application

Start the development server

The development server is configured to run the application on port 8080.

For more information about the development server and its configuration options, visit the webpack documentation site.

npm run dev

Test the application

Navigate to https://localhost:8080. Your browser should display "Hello world!" (See note)

hello-world-view

NOTE: The development server creates a self-signed SSL certificate. If your browser warns you of this, accept the "Potential Security Risk Ahead" warning and proceed to the application.

browser-warning

Clone this wiki locally