簡體   English   中英

React native Typescript 路徑別名無法解析模塊

[英]React native Typescript path alias unable to resolve module

所以基本上,我使用 RN 主頁中的命令行使用 Typescript 創建了我的 React Native: npx react-native init MyApp --template react-native-template-typescript

之后,我運行該項目並成功構建。 但是,當我添加路徑別名以導入我的文件時,它拋出了一個錯誤: Unable to resolve module #folder/file from... could not be found within the project or in these directories: node_modules

我已經在谷歌上關注了一些教程和錯誤解決,但我沒有遇到運氣。

這是我的.babelrc文件(我試圖將文件從 babel.config.js 更改為 .babelrc,正如一些解析器所說,但它仍然沒有用)

{
  "presets": ["module:metro-react-native-babel-preset"],
  "plugins": [
    [
      "module-resolver",
      {
        "root": ["./src"],
        "extensions": [
          ".js",
          ".jsx",
          ".ts",
          ".tsx",
          ".android.js",
          ".android.tsx",
          ".ios.js",
          ".ios.tsx"
        ],
        "alias": {
          "#src/*": [
            "./src/*"
          ],
          "#configs/*": [
            "./src/config/*"
          ],
          "#actions/*": [
            "./src/redux/actions/*"
          ],
          "#reducers/*": [
            "./src/redux/reducers/*"
          ],
          "#store/*": [
            "./src/redux/store/*"
          ]
        }
      }
    ]
  ]
}

tsconfig.json

{
  "compilerOptions": {
    /* Basic Options */
    "target": "esnext", 
    "module": "commonjs",
    "lib": [
      "ES2017",
      "DOM",
      "ES2015",
      "ES2015.Promise"
    ], 
    "allowJs": true, 
    "jsx": "react-native",
    "noEmit": true, 
    "incremental": true,
    "importHelpers": true,
    "isolatedModules": true,
    "strict": true,
    "moduleResolution": "node",
    "baseUrl": ".", 
    "paths": {
      "#src/*": [
        "src/*"
      ],
      "#configs/*": [
        "src/config/*"
      ],
      "#actions/*": [
        "src/redux/actions/*"
      ],
      "#reducers/*": [
        "src/redux/reducers/*"
      ],
      "#store/*": [
        "src/redux/store/*"
      ]
    }, 
    "types": ["jest"],
    "allowSyntheticDefaultImports": true, 
    "esModuleInterop": true, 
    "skipLibCheck": false, 
    "resolveJsonModule": true 
  },
  "exclude": [
    "node_modules",
    "babel.config.js",
    "metro.config.js",
    "jest.config.js"
  ]
}

我的文件夾和文件結構

├───assets
├───components
├───config
│       constants.ts
│
└───redux
    ├───actions
    │       index.ts
    │       stateActions.ts
    │
    ├───reducers
    │       index.ts
    │       stateReducer.ts
    │
    └───store
            index.ts

真的很期待收到你們的答復。 太感謝了

P/s:如果你不介意的話,請看看我的倉庫: https://github.com/NotJackieTruong/rn_test_typescript

要完成這項工作,只需將package.json文件添加到您要訪問的每個目錄中,其中包含一個屬性name 例如:

├───assets
└───components
    └───package.json

package.json內容:

{
  "name": "components"
}

然后你可以像這樣導入:

import SomeComponent from 'components/SomeComponent';

還有一篇很好的文章描述了它是如何工作的。

將此添加到您的tsconfig.json

"include": ["./src/**/*"]

然后重新啟動您的 TypeScript 服務器

Cmd+Shift P然后選擇TypeScript: Restart TS server

tsconfig.json

 "baseUrl": ".", 
 "paths": {
      
      // this is for src directory
      "@*": ["src/*"],
      "@configs/*": ["src/config/*"
      ],

babel.config.js

module.exports = function (api) {
    api.cache(true);
    return {
        presets: ["babel-preset-expo"],
        plugins: [
            [
                "module-resolver",
                {
                    alias: {
                        "@config": "./src/config",
                         ....
                        
                    }
                }
            ]
        ]
    };
};


        }

在 tsconfig.json 中


{
...
   "compilerOptions":{
        ...
       "baseUrl":"."
       "paths":{
            "@folder": "src/folder" <--assuming app logic is in src/ 
        }
   }
}

在 babel.config.js 中

module.exports = {
...
  plugins: [
    ["module-resolver",{
      "alias":{
        "@folder": "./src/folder",
      }
    }]
  ],
};

從模擬器/設備卸載應用程序

重啟 metro 服務器yarn start --reset-cache

構建應用yarn run android/ios

對於那些仍然堅持使用所有解決方案的問題的人,您只需確保以下幾點:-

npm install --save-dev babel-plugin-module-resolver

要么

yarn add --dev babel-plugin-module-resolver

babel.config.js 或 .babelrc

確保這是在 babel 中開發而不是生產<<<<<<<<<<<<< VIP

module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: ['react-native-reanimated/plugin'],
  env: {
    development: { // <<< make sure this is development not production
      plugins: [
        'react-native-paper/babel',
        [
          'module-resolver',
          {
            root: ['./src'],
            extensions: [
              '.js',
              '.jsx',
              '.ts',
              '.tsx',
              '.android.js',
              '.android.tsx',
              '.ios.js',
              '.ios.tsx',
            ],
            alias: {
              '@hooks': ['./src/hooks'],
              '@familyway': ['./src'],
              '@assets': ['./src/Assets'],
              '@components': ['./src/Components'],
              '@constants': ['./src/Constants'],
              '@helpers': ['./src/helpers'],
              '@onboarding': ['./src/onBoarding'],
              '@redux': ['./src/redux'],
              '@screens': ['./src/Screens'],
              '@lib': ['./src/lib'],
              '@containers': ['./src/containers'],
            },
          },
        ],
      ],
    },
  },
};

現在可以使用 tsconfig.json


{
  "compilerOptions": {
    "target": "ES2022",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext",
      "esnext.asynciterable",
      "esnext.intl",
      "esnext.symbol",
      "esnext.array"
    ],
    "allowSyntheticDefaultImports": true,
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "noImplicitAny": true,
    // "noImplicitReturns": true,
    // "noImplicitThis": true,
    "esModuleInterop": true,
    "alwaysStrict": true,
    "noFallthroughCasesInSwitch": true,
    "noUnusedLocals": false,
    "noUnusedParameters": false,
    "module": "commonjs",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "react-native",
    "incremental": true,
    "noEmitOnError": true,
    "baseUrl": "./src",
    "paths": {
      "@hooks/*": ["hooks/*"],
      "@components/*": ["Components/*"],
      "@assets/*": ["Assets/*"],
      "@screens/*": ["Screens/*"],
      "@constants/*": ["Constants/*"],
      "@helpers/*": ["helpers/*"],
      "@onboarding/*": ["OnBoarding/*"],
      "@redux/*": ["redux/*"],
      "@containers/*": ["containers/*"],
      "@lib/*": ["lib/*"]
    }
  },
  "include": [
    "next-env.d.ts",
    "additional.d.ts",
    "src/**/*.ts",
    "src/**/*.js",
    "src/**/*.tsx",
    "./App.tsx",
    "./src/**/*",
    "src/**/*",
    "src/**/*.*"
  ],
  "exclude": ["node_modules"]
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM