创建 React 项目
目标
使用 typescript 创建一个 React 工程,并将 tsx 文件编译为 js。
新建项目目录:study_wepback
创建 tsc 配置
tsconfig.json
{
"compilerOptions": {
"target": "ES6",
"rootDir": "./",
"outDir": "tsc_outputs",
"moduleResolution": "node",
"jsx": "react-jsx"
},
"include": ["src"]
}
tip
rootDir 和 outDir 配合使用,用于指定 tsc 的输出目录
tsc 完整配置参考
tsconfig.json{
"compilerOptions": {
"target": "ES6",
"rootDir": "./",
"outDir": "tsc_outputs",
"lib": ["dom", "dom.iterable", "esnext"],
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"resolveJsonModule": true,
"moduleResolution": "node",
"jsx": "react-jsx"
},
"include": ["src"]
}
初始化 nodejs 环境
在根目录下执行:
npm init
然后一直 enter 就行。
安装 React
在根目录下执行:
npm i react react-dom
npm i @types/react @types/react-dom typescript -D
添加编译脚本
打开 package.json 在 scripts 下添加脚本:
package.json#scripts
"scripts": {
"tsc": "rm -rf tsc_outputs && tsc",
"dev": "npm run tsc",
"test": "echo 'no test'"
}
开始写代码了!
新建一个路径超级长的 ts 代码: 内容如下:
src/screen/membership/pages/index/index.tsx
import { render } from 'react-dom';
const div = document.body.appendChild(document.createElement('div'));
render(<div>Hello webpack5</div>, div);
编译试试
根目录打开 Terminal,输入指令:
npm run dev
就可以看到在 tsc_outputs 目录下已经有编译好的 js 文件了。