所以基本上,我使用 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
真的很期待收到你們的答復。非常感謝
uj5u.com熱心網友回復:
要完成這項作業,只需將package.json檔案添加到您要訪問的每個目錄中,其中包含一個屬性name。例如:
├───assets
└───components
└───package.json
package.json 內容:
{
"name": "components"
}
然后你可以像這樣匯入:
import SomeComponent from 'components/SomeComponent';
還有一篇很好的文章描述了這是如何作業的。
uj5u.com熱心網友回復:
將此添加到您的 tsconfig.json
"include": ["./src/**/*"]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/367140.html
標籤:javascript 反应 打字稿 反应原生 babel-plugin-module-resolver
下一篇:檢測C 類是否有模板方法
