「译」使用Yarn,TypeScript,esbuild,React和Express创建Web应用程序(第2部分)

539次阅读  |  发布于2年以前

这是一个如何使用 Yarn、TypeScript、esbuild、React和Express快速构建web应用的系列教程的第2篇。

本文将指导您使用Yarn包管理器、TypeScript、esbuild,Express和React来构建基本的Web应用程序。在文章的结束部分,您将拥有一个可完全构建和部署的Web应用程序。

  1. [项目配置(第1部分) ]

2 . 添加代码(第2部分)

a. common模块

b. app模块

c. server模块

d. 总结

3 . 构建应用程序(第3部分)

4 . 更进一步(高级篇)

https://github.com/halftheopposite/tutorial-app 查看代码库。

本章节将专注于common、app和server包的基础代码编写。

common模块


common模块主要包含了app和server两个包中的公共脚本和变量。

就本教程而言,该 common模块将非常简单,首先添加一个新的文件夹:

src/index.ts

export const APP_TITLE = 'my-app';

设置需要导出文件的入口。为此,我们将更新package.json文件:

{
  "name": "@my-app/common",
  "version": "0.1.0",
  "license": "UNLICENSED",
  "private": true,
  "main": "./src/index.ts" // Add this line to provide TS with an entrypoint to this package.
}

现在已经完成了common模块打包,文件结构如下所示:

common/
├─ src/
│  ├─ index.ts
├─ package.json

App模块


该模块需要添加来react和 react-dom 两个依赖包

通过执行以下脚本添加:

yarn app add react react-dom
yarn app add -D @types/react @types/react-dom (to add the typings for TypeScript)

添加成功后,您的package.json文件内容如下所示:

{
  "name": "@my-app/app",
  "version": "0.1.0",
  "license": "UNLICENSED",
  "private": true,
  "dependencies": {
    "@my-app/common": "^0.1.0", // Notice that we've added this import manually
    "react": "^17.0.1",
    "react-dom": "^17.0.1"
  },
  "devDependencies": {
    "@types/react": "^17.0.3",
    "@types/react-dom": "^17.0.2"
  }
}

完善app模块的文件目录

  1. public 文件夹,将保存基本HTML页面和其他静态资源
  2. src 文件夹,将包含应用程序的脚本文件

一旦创建了这两个文件夹,我们就可以开始添加HTML文件,该文件将成为我们应用程序的宿主。

public/index.html

<!DOCTYPE html>
<html>
  <head>
    <title>my-app</title>
    <meta name="description" content="Welcome on my application!" />
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <!-- This div is where we will inject our React application -->
    <div id="root"></div>
    <!-- This is the path to the script containing our application -->
    <script src="script.js"></script>
  </body>
</html>

现在我们有了要渲染的页面,我们可以通过添加下面的两个文件夹来实现非常基本但比较使用的React应用程序。

src/index.tsx

import * as React from 'react';
import * as ReactDOM from 'react-dom';

import { App } from './App';

ReactDOM.render(<App />, document.getElementById('root'));

root是我们HTML片段DOM的挂载节点,后续所有的React组件都将注入其中。

src/App.tsx

import { APP_TITLE } from '@flipcards/common';
import * as React from 'react';

export function App(): React.ReactElement {
  const [count, setCount] = React.useState(0);

  return (
    <div>
      <h1>Welcome on {APP_TITLE}!</h1>
      <p>
        This is the main page of our application where you can confirm that it
        is dynamic by clicking the button below.
      </p>

      <p>Current count: {count}</p>
      <button onClick={() => setCount((prev) => prev + 1)}>Increment</button>
    </div>
  );
}

这个简单的App组件将呈现我们应用程序的标题和动态计数器。这将是我们的React树的入口点。可以随意添加您想要的任何代码。

就是这样!我们已经完成了非常基本的React应用程序。目前它并没有太大的作用,但是我们总是可以稍后再使用它并添加更多功能。

App模块最新结构如下所示:

app/
├─ public/
│  ├─ index.html
├─ src/
│  ├─ App.tsx
│  ├─ index.tsx
├─ package.json

Server模块


添加依赖包 cors 和 express,进入项目根目录,运行一下脚本:

yarn server add cors express
yarn server add -D @types/cors @types/express (to add the typings for TypeScript)

添加成功后,您的package.json文件内容如下所示:

{
  "name": "@my-app/server",
  "version": "0.1.0",
  "license": "UNLICENSED",
  "private": true,
  "dependencies": {
    "@my-app/common": "^0.1.0", // Notice that we've added this import manually
    "cors": "^2.8.5",
    "express": "^4.17.1"
  },
  "devDependencies": {
    "@types/cors": "^2.8.10",
    "@types/express": "^4.17.11"
  }
}

完善server模块的文件目录

1 . src 文件夹,包含我们服务器层面所有代码

接下来添加主文件:

src/index.ts

import { APP_TITLE } from '@flipcards/common';
import cors from 'cors';
import express from 'express';
import { join } from 'path';

const PORT = 3000;

const app = express();
app.use(cors());

// Serve static resources from the "public" folder (ex: when there are images to display)
app.use(express.static(join(__dirname, '../../app/public')));

// Serve the HTML page
app.get('*', (req: any, res: any) => {
  res.sendFile(join(__dirname, '../../app/public', 'index.html'));
});

app.listen(PORT, () => {
  console.log(`${APP_TITLE}'s server listening at http://localhost:${PORT}`);
});

这是一个非常基础的Express应用程序,但是如果除了"单页面应用程序"之外没有其他服务的东西,这就是我们需要的。

结构如下所示:

server/
├─ src/
│  ├─ index.ts
├─ package.json

总结


现在所有模块都已准备就绪,我们的小型应用程序具有运行所需的所有代码。但是,由于我们使用的不是纯JavaScript的TypeScript,我们需要一种方法将所有文件转换为可由Node.js(对于我们的服务器)或浏览器(对于我们的React应用程序)可解析和可执行的文件。

此步骤称为转译,下一篇文章将解释如何使用捆绑器构建和服务我们的应用程序。

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8