Ainslie Cleverdon
Ainslie Cleverdon

Reputation: 31

Why can't I have an absolute import (using create-react-app + typescript) in visual studio

So I'm getting started on a project using the react template for a .NET Core MVC WebApp and I'm having some trouble with absolute imports. As far as I understand it, I can set baseUrl in my .tsconfig and that should be the end of it. While this works like a charm in VS Code I cannot seem to get it working in VS 2019.

Here is my basic file/folder structure:

--src
  --Context
    Context.ts
  --App
    App.tsx

When I try import * as Context from 'Context/Context' from App.tsx:

VS2019 gives me the following error: (TS) Cannot find module

However, when I open up the same project/files in VS Code it works as expected.

Could someone please explain to me how I can get the behaviour of VS Code in VS2019 and/or why VS2019 doesn't work the way I'm expecting it to?

Upvotes: 1

Views: 977

Answers (1)

Ainslie Cleverdon
Ainslie Cleverdon

Reputation: 31

I've managed to find what I think to be the solution to this issue. I've been looking through the settings for both VS 2019 and VS Code to see if I could find any blatant mismatches and I came across a setting for Module Specifier Preference [VS 2019] / Import Module Specifier [VS Code] that had very similar options.

In VS Code this was set to "Auto" however in VS 2019 it was set to "Always use relative paths".

I updated this in VS 2019 to "Automatically determine best import path", restarted VS and voila! I'm now able to use absolute path imports for my typescript files.

Since changing this setting I still get IntelliSense errors in the error list window about not being able to find a module when using an absolute import path but this doesn't appear in the editor and I'm able to successfully build and deploy.

The Solution

Go to Options > Text Editor > JavaScript/TypeScript > Formatting > General. Set Module Specifier Preference (TS 2.9 or later) to Automatically determine best import path. Lastly Restart Visual Studio

Upvotes: 2

Related Questions