babel-plugin-root-import icon indicating copy to clipboard operation
babel-plugin-root-import copied to clipboard

Don't let typescript get confused

Open AdrienLemaire opened this issue 5 years ago • 3 comments

Can we add an equivalent to the flow setup for typescript ?

[options]
module.name_mapper='^{rootPathPrefix}/\(.*\)$' -> '<PROJECT_ROOT>/{rootPathSuffix}/\1'

Being new to typescript, I'm not sure how this should be solved.

TS2307: Cannot find module '~/constants'.
Version: typescript 3.1.6      

AdrienLemaire avatar Nov 06 '18 03:11 AdrienLemaire

This might be wrong... but try the vscode instructions. I remember hearing typescript also reads that file.

I'm happy to update the readme if there's a known working solution.

brigand avatar Nov 06 '18 04:11 brigand

I searched a bit and found 2 related resources

https://github.com/niieani/typescript-vs-flowtype#mapping-dynamic-module-names But I didn't understand how to setup a .d.ts file for that purpose

https://www.typescriptlang.org/docs/handbook/module-resolution.html Indeed, this looked very much like your VSCode example

So I added in my tsconfig.json

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

And I could build without getting an error :')

AdrienLemaire avatar Nov 06 '18 05:11 AdrienLemaire

Is there any additional configuration for typescript?

My project was expo javascript and the plugin was working fine with this configurations:

Project structure:

Myproject
  - src/
    AppRoot.js
    - error/
      ErrorBoundary.js
    -all project code inside src
  package.json
  jsconfig.json

jsconfig.json

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

babel.config.js

plugins: [
      ['babel-plugin-root-import',
        {
          "rootPathSuffix": "src",
          "rootPathPrefix": "~"
        }
      ],
    ],

Import use AppRoot.js

import ErrorBoundary from '~/error/ErrorBoundary';

Then i converted to typescript, replaced jsconfig to tsconfig, and geting error to resolver when running the app

Unable to resolve "../error/ErrorBoundary" from "src\AppRoot.tsx"

Vscode typescript is working fine, it resolves the path in intellisense so i think im missing something in babel.config.js

importing without slash it works

import ErrorBoundary from '~error/ErrorBoundary';

in javascript it was working with slash ~/ in typescript its trying to lev one directory up ../ any ideia how to fix that?

allandiego avatar Apr 17 '20 14:04 allandiego