This is the 4th day of my participation in the August More Text Challenge

Add typescrip support

yarn add --dev typescript @types/jest @types/react @types/react-native @types/react-test-renderer
Copy the code

Add a TypeScript configuration file. Create a tsconfig.json file in the root directory of your project:

{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "isolatedModules": true,
    "jsx": "react",
    "lib": ["es6"],
    "moduleResolution": "node",
    "noEmit": true,
    "strict": true,
    "target": "esnext"
  },
  "exclude": [
    "node_modules",
    "babel.config.js",
    "metro.config.js",
    "jest.config.js"
  ]
}
Copy the code

Create a jest.config.js file to configure Jest to use TypeScript:

module.exports = {
  preset: 'react-native',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node']
};
Copy the code

Rename the JavaScript file to *.tsx:

Keep the./index.js entry file, otherwise you will encounter problems when packaging the production version.

Configure a custom path alias

Edit your custom path map for tsconfig.json. Make anything in the root directory of SRC available, without the previous path reference, and allow access to any test files using the following command: test/ file.tsx

{
  "compilerOptions": {
    "allowJs": true."allowSyntheticDefaultImports": true."esModuleInterop": true."isolatedModules": true."jsx": "react"."lib": ["es6"]."moduleResolution": "node"."noEmit": true."strict": true."target": "esnext"."baseUrl": "."."paths": {
      "@src/*": ["src/*"]."@pages/": ["src/pages/"],}},"exclude": [
    "node_modules"."babel.config.js"."metro.config.js"."jest.config.js"]}Copy the code

Add dependency to babel-plugin-module-resolver

yarn add --dev babel-plugin-module-resolver
# or
npm install --save-dev babel-plugin-module-resolver
Copy the code

3. Finally, configure your babel.config.js (note that your syntax is different from your babel.config.js tsconfig.json) :

module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
    [
      'module-resolver',
      {
        root: ['./src'],
        extensions: ['.ios.js', '.android.js', '.js', '.ts', '.tsx', '.json'],
        alias: {
          '@src': './src/',
          '@pages': './src/pages/',
        },
      },
    ],
  ],
};

Copy the code

Pay attention to

How do I troubleshoot errors during the configuration? Mouse over the path you introduced to copy the full path of the map. Contrast colors.

reference

RN’s official website