1. 程式人生 > 其它 >雜項(1) creat-react-app ts 使用webpack別名

雜項(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" ], }

儲存,重啟