How do I configure absolute paths for imports in TypeScript based React Native apps?

前端 未结 5 1947
生来不讨喜
生来不讨喜 2020-12-29 07:27

In order to avoid \'../../../../\' style relative imports in a TypeScript based React Native app, I would like to configure the app so that I can use absolute imports instea

5条回答
  •  囚心锁ツ
    2020-12-29 08:25

    Summary:

    The npm package babel-plugin-module-resolver is needed, as well as some configuration in tsconfig.json and babel.config.js


    Step by step:

    1. npm install babel-plugin-module-resolver (or yarn add babel-plugin-module-resolver)

    2. tsconfig.json: Add "baseUrl": "." to compilerOptions

    3. babel.config.js: Add a key named plugins with the following value:

    [
        [
          'module-resolver',
          {
            extensions: [
              '.js',
              '.jsx',
              '.ts',
              '.tsx',
              '.android.js',
              '.android.tsx',
              '.ios.js',
              '.ios.tsx'
            ],
            root: ['.']
          }
        ]
      ]
    

    Complete configuration:

    tsconfig.json:

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

    babel.config.js:

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

    This is for a clean new project created using npx react-native init MyTestApp --template typescript on React Native version 0.60.5

提交回复
热议问题