简体   繁体   中英

Why don't absolute paths work when importing typescript files into other typescript files but are otherwise ok, in a React Native Project?

Backstory:

I am gradually converting an existing React Native project to TypeScript. Absolute paths have been working for years based on my babelrc configuration.

Problem:

Since adding TypeScript, absolute paths work only in the following scenarios:

  • importing js files into other js files
  • importing ts files into js files
  • importing js files into ts files

The thing that does not work is:

  • importing ts files into other ts files

It appears to work in VSCode but when I try to build my app, I get the infamous:

{insert file here} could not be found within the project or in these directories: node_modules, etc.

I have spent weeks trying to figure this out. Absolute paths with TypeScript seems to be a challenge a lot of people run into. I've tinkered with my babelrc , tsconfig , eslintrc , and metro.config.js with a myriad of combinations and additions/subtractions. I've installed dependencies, I've tried everything the error suggests(deleting caches, restarting, etc.). I've played with the import statements and scoured the docs until I was black and blue, reinstalled node_modules and pods .

The ONLY thing that has worked(besides relative imports, but ew) is adding a package.json to the folder I am trying to import from like so:

{
  "name": "app"
}

This seems simple enough but I can't accept that this is the only way. And as I convert more and more files, I don't really want to have to keep sprinkling package.json s everywhere like some overworked typescript fairy:)

I don't want to make this too long so if anyone thinks it would be beneficial to see my config files, I can for sure add them. Especially hoping for an answer referenced by official sources. Super appreciate anyone's help!

Here are a few things you can try to troubleshoot the issue:

Make sure you are using the correct syntax for absolute imports in TypeScript. In TypeScript, you can use the paths option in your tsconfig.json file to configure absolute paths for your imports. The syntax should look something like this:

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

This allows you to use a @ symbol as a prefix for your imports, and the compiler will replace it with the value of the baseUrl option (in this case, ./src).

For example, you could use the following import statement:

import { SomeModule } from '@/utils/someModule';

This would be equivalent to:

import { SomeModule } from './src/utils/someModule';

Make sure you have correctly configured your build tools to handle TypeScript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM