react +Ts配置项目路径别名
基于
System:
OS: Windows 10 10.0.19045
CPU: (12) x64 AMD Ryzen 5 5600H with Radeon Graphics
Memory: 6.29 GB / 15.36 GB
Binaries:
Node: 16.18.1 - C:\Nodejs install\node.EXE
npm: 8.19.2 - C:\Nodejs install\npm.CMD
Browsers:
Edge: Spartan (44.19041.1266.0), Chromium (108.0.1462.76)
Internet Explorer: 11.0.19041.1566
Packages:
webpack: ^5.75.0 => 5.75.0
webpack-cli: ^5.0.1 => 5.0.1
我们需要借助craco去配置(因为我不想吧webpack的config全暴露出来)
一 安装npm i @craco/craco@alpha -D
因为我们的webpack安装的是最新版本由于craco与webpack的版本不兼容所以我们需要安装alpha版本
二 配置一下 craco.config.js
文件
const path = require('path')
const resolve = (dir) => path.resolve(__dirname, dir)
module.exports = {
webpack: {
alias: {
'@': resolve('src')
}
}
}
三 在项目根目录中的tsconfig.json文件中加上
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
我们tsconfig文件长这样
{
"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",
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
},
"include": [
"src"
]
}