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

前端 未结 5 2036
生来不讨喜
生来不讨喜 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:15

    Requirement

    // Meh
    import config from '../../../../../../../config';
    
    // Awesome!
    import config from '@cuteapp/config';
    

    How To

    1. Add this babel plugin package
    yarn add --dev babel-plugin-module-resolver
    
    1. My babel.config.js
    module.exports = {
      presets: ['module:metro-react-native-babel-preset'],
      plugins: [
        [
          require.resolve('babel-plugin-module-resolver'),
          {
            cwd: 'babelrc',
            extensions: ['.ts', '.tsx', '.js', '.ios.js', '.android.js'],
            alias: {
              '@cuteapp': './app'
            }
          }
        ],
        'jest-hoist'
      ]
    };
    
    1. My tsconfig.json
    {
      "compilerOptions": {
        "allowJs": true,
        "allowSyntheticDefaultImports": true,
        "esModuleInterop": true,
        "isolatedModules": true,
        "jsx": "react",
        "lib": ["es2015", "es2015.promise", "es2016.array.include", "dom"],
        "strict": true,
        "moduleResolution": "node",
        "baseUrl": "./",
        "paths": {
          "@cuteapp/*": ["app/*/index", "app/*"]
        },
        "noEmit": true,
        "resolveJsonModule": true,
        "target": "esnext",
        "types": ["jest"]
      },
      "exclude": ["node_modules", "babel.config.js", "metro.config.js"]
    }
    
    1. That's it.

提交回复
热议问题