Express.js TypeScript와 React TypeScript 프로젝트 만들기
36554 단어 spanishtypescriptjavascriptreact
TypeScript로 React 및 Express.js 프로젝트 생성 | 코딩PR
React 및 Express.js와 TypeScript를 사용하여 시작 공식 생성
codingpr.com
1. Su entorno de Node를 구성합니다.
Terminal
mkdir simple-react-form
cd simple-react-form
Terminal
npm init -y
code .
2. Express.js 및 TypeScript 구성.
Install through npm or yarn
npm install cors dotenv express
npm install -D typescript @types/cors @types/express @types/node concurrently nodemon
Config
npx tsc --init
tsconfig.json
{
"compilerOptions": {
"target": "es2016",
"jsx": "preserve",
"module": "commonjs",
"allowJs": true,
"outDir": "./dist",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
},
"exclude": [
"client",
"dist",
"node_modules"
]
}
package.json
{
"scripts": {
"build": "npx tsc",
"start": "node dist/index.js",
"dev": "concurrently \"npx tsc --watch\" \"nodemon -q dist/index.js\"",
"test": "echo \"Error: no test specified\" && exit 1"
},
}
index.ts
import dotenv from "dotenv";
import express, { Express, Request, Response } from "express";
import path from "path";
import cors from "cors";
dotenv.config();
const app: Express = express();
app.use(express.json());
app.use(cors());
app.get('/', (req: Request, res: Response) => {
res.send('<h1>Hello World From the Typescript Server!</h1>')
});
const port = process.env.PORT || 8000;
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
});
Terminal
npm run build
npm run dev
3. 반응 및 TypeScript 구성.
Terminal
npx create-react-app client --template typescript
Git Bash
$ cd client
$ rm -rf .git
Git Bash
$ cd src
$ mkdir components
$ mkdir utils
Git Bash
$ cd components
$ mkdir form-input
$ cd form-input
$ touch form-input.tsx
client/src/components/form-input/form-input.tsx
import { InputHTMLAttributes, FC } from "react";
import './form-input.css';
type FromInputProps = { label: string } &
InputHTMLAttributes<HTMLInputElement>;
const FormInput: FC<FromInputProps> = ({ label, ...otherProps }) => {
return (
<div className="group">
<input {...otherProps} />
{
label &&
<div className="form-input-label">
{label}
</div>
}
</div>
);
}
export default FormInput;
client/src/utils/data-utils.ts
export const getData = async <T>(
url: string,
email: string,
password: string
)
: Promise<T> => {
const res = await fetch(url, {
method: 'Post',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({ email, password })
});
return await res.json();
}
client/src/App.tsx
import { useState, ChangeEvent, FormEvent } from "react";
import { ReactComponent as Logo } from "./logo.svg";
import { getData } from "./utils/data-utils";
import FormInput from './components/form-input/form-input';
import './App.css';
// declaraciones TypeScript
type User = {
id: number,
name: string,
email: string,
password: string
}
const defaultFormFields = {
email: '',
password: '',
}
const App = () => {
// react hooks
const [user, setUser] = useState<User | null>()
const [formFields, setFormFields] = useState(defaultFormFields)
const { email, password } = formFields
const resetFormFields = () => {
return (
setFormFields(defaultFormFields)
);
}
// handle input
const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
const { name, value } = event.target
setFormFields({...formFields, [name]: value })
}
const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault()
try {
// Llamada API
const res:User = await getData(
'http://localhost:8000/login', email, password
)
setUser(res);
resetFormFields()
} catch (error) {
alert('User Sign In Failed');
}
};
const reload = () => {
setUser(null);
resetFormFields()
};
return (
<div className='App-header'>
<h1>
{ user && `Welcome! ${user.name}`}
</h1>
<div className="card">
<Logo className="logo" />
<h2>Sign In</h2>
<form onSubmit={handleSubmit}>
<FormInput
label="Email"
type="email"
required
name="email"
value={email}
onChange={handleChange}
/>
<FormInput
label="Password"
type='password'
required
name='password'
value={password}
onChange={handleChange}
/>
<div className="button-group">
<button type="submit">Sign In</button>
<span>
<button type="button" onClick={reload}>Clear</button>
</span>
</div>
</form>
</div>
</div>
);
}
export default App;
4. 기존의 새로운 TypeScript 서비더의 집합체.
index.ts
interface FormInputs {
email: string,
password: string
}
// Array de usuarios con fines de prueba
const users = [
{
id: 1,
name: 'Maria Doe',
email: '[email protected]',
password: 'maria123'
},
{
id: 2,
name: 'Juan Doe',
email: '[email protected]',
password: 'juan123'
}
];
// route login
app.post('/login', (req: Request, res: Response) => {
const { email, password }:FormInputs = req.body;
const user = users.find(user => {
return user.email === email && user.password === password
});
if (!user) {
return res.status(404).send('User Not Found!')
}
return res.status(200).json(user)
});
Terminal
npm run dev
cd client
npm start
Cómo subir un proyecto de React y Express TypeScript a Heroku .
Reference
이 문제에 관하여(Express.js TypeScript와 React TypeScript 프로젝트 만들기), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/denisseab/integra-react-typescript-con-expressjs-typescript-1gb1텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)