react @craco/craco的配置使用 配置路径别名 @

2022-05-05  本文已影响0人  摩了个羯
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项目
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 用来配置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跑项目, 此时你可以看到@已经可以当src绝对路径使用了 (注意的是, Home如果是.tsx, 不要写后缀)
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
上一篇下一篇

猜你喜欢

热点阅读