1. 終端命令
npm i @craco/craco
2. 新增 ./craco.config.js 文件
const path = require('path')
module.exports = {
// webpack 配置
webpack: {
// 配置別名
alias: {
// 約定:使用 @ 表示 src 文件所在路徑
'@': path.resolve(__dirname, 'src'),
// 約定:使用 @scss 表示全局 SASS 樣式所在路徑
// 在 SASS 中使用
'@scss': path.resolve(__dirname, 'src/assets/styles')
}
}
}
3. 修改./package.json的script配置
...
"scripts": {
"start": "craco start",
"build": "craco build",
"test": "craco test",
"eject": "react-scripts eject"
}
...
4. npm start 跑react項(xiàng)目
Compiled successfully!
You can now view geek-demo in the browser.
Local: http://localhost:3000
On Your Network: http://192.168.1.101:3000
Note that the development build is not optimized.
To create a production build, use npm run build.
webpack compiled successfully
No issues found.
5. 新增./path.tsconfig.json 使用extends 用來(lái)配置tsconfig.json
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"@/*": ["src/*"],
"@scss/*": ["src/assets/styles/*"]
}
}
}
6. 修改./tsconfig.json, 新增一條配置, "extends": "./path.tsconfig.json"
{
"extends": "./path.tsconfig.json",
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
...
}
7. 重啟vscode, npm start跑項(xiàng)目, 此時(shí)你可以看到@已經(jīng)可以當(dāng)src絕對(duì)路徑使用了 (注意的是, Home如果是.tsx, 不要寫(xiě)后綴)
import Home from '@/pages/Home/Home'
const App = () => {
console.log(Home)
return (
<div className="app">
<h2>App組件</h2>
<Home></Home>
</div>
)
}
export default App
import { http } from '@/utils/http'
function Home() {
console.log(http)
return (
<div>
<h2>Home組件</h2>
</div>
)
}
export default Home