Pesquisa de site

javascript - React native Typescript alias de caminho não consegue resolver módulo


então basicamente, eu criei meu React Native com Typescript usando a linha de comando na página inicial do RN: npx react-native init MyApp --template react-native-template-typescript

Depois disso, eu executei o projeto e ele foi construído com sucesso. No entanto, quando adicionei o alias de caminho para importar meu arquivo, ocorreu um erro: Não foi possível resolver o módulo #folder/file de ... não pôde ser encontrado dentro do projeto ou nestes diretórios: node_modules

Eu já segui alguns tutoriais e soluções de bugs no Google, mas não tive sucesso.

Aqui está meu arquivo .babelrc (eu tentei mudar o arquivo de babel.config.js para .babelrc como algum resolvedor disse, mas ainda assim não funcionou)

{
  "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"
  ]
}

Minha estrutura de pastas e arquivos

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

Realmente ansioso para receber as respostas de vocês. Muito obrigado

P.S.: se você não se importar, por favor, dê uma olhada no meu repositório: https://github.com/NotJackieTruong/rn_test_typescript

Resposta #1

Para expo v49+:

  1. module-resolver não é necessário, você pode removê-lo do babel-config

  2. Adicione em app.json:

{
  "expo": {
    "experiments": {
      "tsconfigPaths": true
    }
  }
}
  1. Defina paths como de costume em tsconfig.json:
{
  "compilerOptions": {
    "paths": {
      "@/*": [
        "src/*"
      ]
    }
  },
  "extends": "expo/tsconfig.base"
}

Resposta #2

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",
                         ....
                        
                    }
                }
            ]
        ]
    };
};


        }

Artigos relacionados