react - 设置@别名 问题

43 阅读1分钟

方案一 eject

这个是react在 package.json 自带的命令。算是react给我们留的配置 webpack 的一种途径

第一步,执行 eject 命令

yarn eject

执行后,会弹出提示

1.png

直接 y 就行了

第二步,修改webpack配置

执行完第一步后,根目录会多出两个文件夹 configscripts,找到 config 配置文件下的 webpack.config.js 文件,添加配置代码。

  alias: {
    // Support React Native Web
    // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
    "react-native": "react-native-web",
    // Allows for better profiling with ReactDevTools
    ...(isEnvProductionProfile && {
      "react-dom$": "react-dom/profiling",
      "scheduler/tracing": "scheduler/tracing-profiling",
    }),
    ...(modules.webpackAliases || {}),
    // /@ 别名配置
    "/@": path.resolve("./src/"),
  },

第三步,修改ts配置文件

找到目录的 tsconfig.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": false,
    "noEmit": true,
    "jsx": "react-jsx",
    
    // 下面两个是需要添加的配置
    "baseUrl": ".",
    "paths": {
      "/@/*": ["./src/*"]
    }
}

第四步,使用方法

import Home from "/@/views/home";