airbnb / babel-plugin-inline-react-svg

A babel plugin that optimizes and inlines SVGs for your React Components.
MIT License
474 stars 92 forks source link

Allow Typescript absolute path alias #97

Closed lukasoppermann closed 3 years ago

lukasoppermann commented 3 years ago

Hey, currently the absolute paths from my typescript tsconfig.json are not resolved.

{
  "compilerOptions": {
    "paths": {
      "@svgs/*": [
        "svgs/*"
      ]
  }
}

Doing import Dog from '@svgs/dog.svg' results in an error: Cannot find module '@svgs/dog.svg' from '/Users/lukasoppermann/Repos/next-app/components'

Is there a way to make this work?

ljharb commented 3 years ago

The way is to get rid of all typescript (and webpack) aliases, and only do path aliasing with babel (and, to only do transpiling with babel). Unfortunately it’s likely not a small amount of effort.

lukasoppermann commented 3 years ago

Hey @ljharb, thanks for the quick reply. I use nextjs (getting started) and have only 5 typescript aliases. Do you know if nextjs uses babel only?

I feel this should be easy to do for me, so I'll give it a spin, but does typescript recognize babel aliases in vs code?

ljharb commented 3 years ago

I’m not familiar with nextjs, you’d have to file an issue there.

That’s a good point; with this approach, even if you’re only using typescript for typechecking, it still needs a way to understand the specifiers to check types. I’m not sure the best solution here. Another option is to not use any aliases and use the actual filesystem/package paths for everything.

either way, this is far out of the scope of a babel plugin, so I’ll close this.

lukasoppermann commented 3 years ago

It seems to be working fine just by installing the babel module-resolver and adding the following to the .babelrc and leaving the tsconfig.json as is.


// babelrc
{
  "presets": ["next/babel"],
  "plugins": [
    "inline-react-svg",
    ["module-resolver", {
      "root": ["./"],
      "alias": {
        "@svgs": "./svgs"
      }
    }]
  ]
}
///
ljharb commented 3 years ago

Good call; as long as you're OK duplicating the config in both babel and TS configs, that should work fine.