entwicklerstube / babel-plugin-root-import

Add the opportunity to import modules by the root path
https://npmjs.com/babel-plugin-root-import
MIT License
1.18k stars 76 forks source link

Don't let typescript get confused #114

Open AdrienLemaire opened 6 years ago

AdrienLemaire commented 6 years ago

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      
brigand commented 6 years ago

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.

AdrienLemaire commented 6 years ago

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 :')

allandiego commented 4 years ago

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?