所以基本上,我使用 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
我已经在 Google 上关注了一些教程和错误解决方案,但我没有遇到任何运气。
这是我的.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