杂项(1) creat-react-app ts 使用webpack别名

前言

  ts下使用webpack别名和js不一样,出了配置webpack的alias配置之外,还需要对ts的配置tsconfig.json文件进行配置

暴露配置文件

  本文假定你使用了create-react-app进行的项目构建

npm run eject //暴露配置文件

找到config/webpack.config.js

  在alias配置项中增加配置

 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(__dirname, "../src"),//添加自定义别名
      },

修改tsconfig.json

  进入根目录下的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": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "baseUrl": "src", //新增此配置
    "paths":{ //新增此配置
      "@/*":["*"]
    }
  },
  "include": [
    "src"
  ],
}

保存,重启

 

posted @ 2021-06-21 17:04  眼里有激光  阅读(222)  评论(0编辑  收藏  举报