- 初始化项目
1 2 3 | npm install -g create-react-app create-react-app my-app --typescript |
具体参考: https://www.html.cn/create-react-app/docs/adding-typescript/
- 安装插件以修改配置
1 | yarn add react-app-rewired customize-cra |
1 2 3 4 5 6 7 8 9 | /* package.json */ "scripts": { - "start": "react-scripts start", + "start": "react-app-rewired start", - "build": "react-scripts build", + "build": "react-app-rewired build", - "test": "react-scripts test --env=jsdom", + "test": "react-app-rewired test --env=jsdom", } |
- 然后在项目根目录创建一个 config-overrides.js 用于修改默认配置, 并加入别名配置
1 2 3 4 5 6 7 8 9 10 11 12 13 | const { override, fixBabelImports, addWebpackAlias } = require('customize-cra'); const path = require("path"); module.exports = override( fixBabelImports('import', { libraryName: 'antd-mobile', style: 'css', }), addWebpackAlias({ // add your alias '@' : path.resolve(__dirname, 'src') }) ) |
- 在上一步中我们加入了alias也就是别名, 但是仅仅这样还是不够的,如果我们在代码中使用 别名去引入其他文件还是会编译报错,在ts项目中,还需要修改 tsconfig.json, 在其中加入paths
// 在tsconfig.json中最后一行追加
1 | "extends": "./paths.json" |
在tsconfig.json同级目录新建paths.json
1 2 3 4 5 6 7 8 | { "compilerOptions": { "baseUrl": "src", "paths": { "@/*": ["*"] } } } |
// 注意这里不能直接在tsconfig.json中添加 paths配置,一定放要在扩展配置中
- 最后再搭配上vscode,就可以开始愉快地coding,享受ts给你带来的超爽体验了~