一.使用ts構建的react項目,如今tsconfig.json文件中配置baseUrl和paths。因爲直接在tsconfig.json裏面配置paths字段後重啓項目,會將配置好的paths自動移除,因此採用extends字段讓tsconfig.json繼承自定義的tsconfig.paths.json。步驟以下:node
1.如今項目根目錄下建立tsconfig.paths.json文件,內容以下:react
{ "compilerOptions": { "baseUrl": "./", "paths": { "@/*": ["src/*"] } } }
2.在tsconfig.json中繼承tsconfig.paths.json文件,使用了tsconfig.json提供的extends字段:json
{ "compilerOptions": { "target": "es5", "lib": [ "dom", "dom.iterable", "esnext" ], "allowJs": true, "skipLibCheck": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "noFallthroughCasesInSwitch": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx", "experimentalDecorators": true }, "include": [ "src" ], "extends": "./tsconfig.paths.json" }
3.配置完tsconfig.json文件後,就須要安裝customize-cra和react-app-rewired庫:
app
yard add customize-cra react-app-rewired --save-devdom
4.修改package.json:ide
"scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test", "eject": "react-app-rewired eject" }
5.在項目根目錄下新建config-overrides.js(只能是js文件,別建成ts文件了),內容以下:ui
const { override, addDecoratorsLegacy, addWebpackAlias } = require("customize-cra"); const path = require("path"); module.exports = override( addDecoratorsLegacy(), addWebpackAlias({ "@": path.resolve(__dirname, './src') }) );
6.配置完成,能夠在項目中使用如:import App from "@/App"的導入方式了es5
customize-cra