Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

baseUrl in tsconfig is not supported #23

Closed
nkovacic opened this issue Oct 3, 2018 · 22 comments
Closed

baseUrl in tsconfig is not supported #23

nkovacic opened this issue Oct 3, 2018 · 22 comments
Assignees
Labels
enhancement New feature or request

Comments

@nkovacic
Copy link

nkovacic commented Oct 3, 2018

Expected results

Setting baseUrl in tsconfig.json should enable absolute import paths.

{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "isolatedModules": true,
    "jsx": "react-native",
    "lib": ["es6"],
    "moduleResolution": "node",
    "noEmit": true,
    "strict": true,
    "strictPropertyInitialization": false,
    "target": "esnext",
    "baseUrl": "./src",
    "paths": {
      "@assets/*": ["assets/*"]
    }
  },
  "exclude": ["node_modules"]
}

index.ts

import Images from 'assets/images';

Observed results

What happened?
This error appears: error: bundling failed: Error: Unable to resolve module assets/images

Logs

Loading dependency graph, done.
error: bundling failed: Error: Unable to resolve module `assets/images` from `D:\App\src\pages\Splash\Splash.tsx`: Module `assets/images` does not exist in the Haste module map

This might be related to https://github.com/facebook/react-native/issues/4968
To resolve try the following:
  1. Clear watchman watches: `watchman watch-del-all`.
  2. Delete the `node_modules` folder: `rm -rf node_modules && npm install`.
  3. Reset Metro Bundler cache: `rm -rf /tmp/metro-bundler-cache-*` or `npm start -- --reset-cache`.
  4. Remove haste cache: `rm -rf /tmp/haste-map-react-native-packager-*`.
    at ModuleResolver.resolveDependency (D:\App\node_modules\metro\src\node-haste\DependencyGraph\ModuleResolution.js:209:1301)
    at ResolutionRequest.resolveDependency (D:\App\node_modules\metro\src\node-haste\DependencyGraph\ResolutionRequest.js:83:16)
    at DependencyGraph.resolveDependency (D:\App\node_modules\metro\src\node-haste\DependencyGraph.js:238:485)
    at Object.resolve (D:\App\node_modules\metro\src\lib\transformHelpers.js:180:25)
    at dependencies.map.result (D:\App\node_modules\metro\src\DeltaBundler\traverseDependencies.js:311:29)
    at Array.map (<anonymous>)
    at resolveDependencies (D:\App\node_modules\metro\src\DeltaBundler\traverseDependencies.js:307:16)
    at D:\App\node_modules\metro\src\DeltaBundler\traverseDependencies.js:164:33
    at Generator.next (<anonymous>)
    at step (D:\App\node_modules\metro\src\DeltaBundler\traverseDependencies.js:266:307)
@emin93
Copy link
Member

emin93 commented Oct 3, 2018

Hi @nkovacic,

Thank you for creating an extended issue.

Sadly the .tsconfig can only be used for type checking and not for transpilation. That's because since React Native 0.57, TypeScript has been added as a preset for Babel 7 (https://blogs.msdn.microsoft.com/typescript/2018/08/27/typescript-and-babel-7/) and the TypeScript compiler is not being used anymore.

I have not yet found a solution for that issue and open for contributions.

@emin93 emin93 self-assigned this Oct 3, 2018
@emin93 emin93 added the bug Something isn't working label Oct 3, 2018
@nkovacic
Copy link
Author

nkovacic commented Oct 5, 2018

Is there any other way to atleast set a base path, so that absolute paths can be used?
Because relative path imports like these are really a pain to mantain...
import { currentStepSelector } from '../../../../../modules/auth/reducer';

@emin93
Copy link
Member

emin93 commented Oct 5, 2018

I never used absolute paths but I quickly checked and there seems to be a way: https://medium.com/@davidjwoody/how-to-use-absolute-paths-in-react-native-6b06ae3f65d1

@emin93 emin93 added enhancement New feature or request and removed bug Something isn't working labels Oct 16, 2018
@solkaz
Copy link

solkaz commented Oct 16, 2018

The solution to this is to add babel-plugin-module-resolve and then mimic the baseUrl/paths setup in your Babel config to transform your import paths like TypeScript would.

@nkovacic for your configuration, your .babelrc should similar to this:

{
    "presets": ["module:metro-react-native-babel-preset"],
    "plugins": [
        [
            "module-resolver",
            {
                "root": ["./src"],
                "alias": {
                    "@assets/*": "assets/*"
                }
            }
        ]
    ]
}

@MR03web
Copy link

MR03web commented Oct 17, 2018

same question and I used solution of @solkaz, little different.

.babelrc

    [
      "module-resolver",
      {
        "alias": {
          "@kit": "./src/kit"
        }
      }
    ]

tsconfig.json

    "baseUrl": ".",
    "paths": {
      "@kit/*": ["src/kit/*"]
    }

@nkovacic
Copy link
Author

@solkaz tried your solution and there seems to be a collision between ./src folder and some react-native internals. Probably should work in other JavaScript projects.

@solkaz
Copy link

solkaz commented Oct 19, 2018

@nkovacic what errors were you getting?

@larryranches
Copy link

Also having this issue with setting baseUrl in the tsconfig. Any valid workarounds or solutions on this?

@nkovacic
Copy link
Author

Even when changing the src main folder to app, paths still do not work. Can anyone share a complete example?

@afiouni
Copy link

afiouni commented Apr 18, 2019

The babel-plugin-module-resolver documentation shows how to use regular expressions to address this. So after some experimenting, this is a running example:

tsconfig.json

"baseUrl": ".",
    "paths": {
      "xyz": ["src/components/xyz/index"],
      "xyz/*": ["src/components/xyz/*"],
      "components/*": ["src/components/*"],
    }

babel.config.js

module.exports = {
  presets: ["module:metro-react-native-babel-preset"],
  plugins: [
    [
      "module-resolver",
      {
        alias: {
          "xyz": ["./src/components/xyz/"],
          "components/(.+)": "./src/components/\\1",
        }
      }
    ]
  ]
}

Adding a special path for index imports was the only way to make it work in my experience

Using it is straight forward:

import Something from 'xyz';
import { SomethingElse } from 'components/SomethingElse';

Took some trial and error but it's working fine now.

@dawsonc623
Copy link

This solution did not work for me. As far as I can tell, the babel.config.js file is not even being read in my environment; I put some gibberish at the bottom of the file, and the application still built and loaded (minus the fact this error came up).

I am on React Native 0.59.5 - I am not sure if that could explain the difference in behavior.

@guatedude2
Copy link

I'm seeing the same issue

@mrruby
Copy link

mrruby commented Sep 4, 2019

Adding babel-plugin-module-resolve and updating babel.config.js with tsconfig.js works fine in my 0.60.5 app

@radko93
Copy link
Collaborator

radko93 commented Sep 10, 2019

I don't think this is related to this template if you would like to have this feature consider submitting a PR.

@radko93 radko93 closed this as completed Sep 10, 2019
@resolritter
Copy link

I've tried other solutions in this thread, in addition to trying to work around the issue with "@babel/register". It did not work.

What worked for me was to edit metro.config.js and use extraNodeModules.


Since I have this in tsconfig.json

{
  "compilerOptions": {
    "baseUrl": "."

And I want to import from "[root]/src" as "src/...", here's my full metro.config.js configuration:

const path = require("path")

module.exports = {
  resolver: {
    extraNodeModules: {
      "src": path.resolve(__dirname, 'src'),
    }
  },
  transformer: {
    getTransformOptions: async () => ({
      transform: {
        experimentalImportSupport: false,
        inlineRequires: false,
      },
    }),
  },
}

If your module still isn't being found, try tweaking sourceExts.

@juanlet
Copy link

juanlet commented Apr 26, 2020

Neat solution @resolritter . That worked for me. Thanks!

@apedroferreira
Copy link

For everyone for whom using babel-plugin-module-resolve didn't work and is using Expo:
Try running your project with expo start --clear to clear your Javascript transform cache, it worked for me.

@kelvinndmo
Copy link

Saved my life @apedroferreira

@revgum
Copy link

revgum commented Nov 15, 2021

👍 to @apedroferreira

@Bi0max
Copy link

Bi0max commented Aug 25, 2022

Probably this could help somebody. It helped me: https://www.reactnativeschool.com/how-to-setup-path-alias-in-a-react-native-typescript-app

@DarkHaker03
Copy link

Thank u @resolritter , your solution really helped me )

@gabriel-hahn
Copy link

Thanks @apedroferreira! It worked for me with the module-resolver solution and resetting the cache too, but for React Native CLI: npm start -- --reset-cache

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests