Search code examples
typescriptvisual-studio-codebabeljs

Typescript & babel-plugin-module-resolver: VS Code doesn't resolve imports


I'm currently learning to use typescript, but I have an issue with VS Code. I've set up a basic project with Babel 7 and a couple of plugins. I run the script using the command npm run dev. Here is the full list of my dependencies:

//package.json
"scripts": {
  "dev": "nodemon src/index.ts --extensions \".ts\" --exec babel-node"
},
"devDependencies": {
  "@babel/cli": "^7.1.2",
  "@babel/core": "^7.1.2",
  "@babel/helper-plugin-utils": "^7.0.0",
  "@babel/node": "^7.0.0",
  "@babel/plugin-proposal-async-generator-functions": "^7.1.0",
  "@babel/plugin-proposal-class-properties": "^7.1.0",
  "@babel/plugin-proposal-decorators": "^7.1.2",
  "@babel/plugin-proposal-optional-catch-binding": "^7.0.0",
  "@babel/plugin-proposal-optional-chaining": "^7.0.0",
  "@babel/plugin-transform-modules-commonjs": "^7.1.0",
  "@babel/plugin-transform-typescript": "^7.1.0",
  "babel-plugin-module-resolver": "^3.1.1"
}

Below are the content of my 2 .ts files.

// src/script.ts
export default function (arg:string): string {
  return arg;
};

// src/index.ts
import Fn from "@/script";
console.log( Fn("Hello World") );

And here is my Babel config file:

//babel.config.js
module.exports = {
  "plugins": [
    ["@babel/plugin-transform-typescript"],
    ["@babel/plugin-transform-modules-commonjs"],
    ["@babel/plugin-proposal-async-generator-functions"],
    ["@babel/plugin-proposal-optional-catch-binding"],
    ["@babel/plugin-proposal-optional-chaining"],
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    ["@babel/plugin-proposal-class-properties", { "loose": true }],//must be after @babel/plugin-proposal-decorators

    ["module-resolver", {
      //"root": ["./src", "./test"],
      "alias": {
        //"__root": ".",
        "@": "./src",
        //"#": "./src/assets",
        //"_": "./src/assets/_",
        //"!": "./static"
      },
    }]
  ]
};

And my Typescript config file:

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

When I run this code, it looks good and I see "Hello World" in my console. However, VS Code doesn't seem to understand the path "@/script". It is underlined in red with a tooltip that says

[ts] Cannot find module '@/script'.

I don't have this problem if I don't use the babel-plugin-module-resolver plugin, with the path "./script" instead. Is there a way to fix that?

Thanks!


Solution

  • Your syntax for paths in tsconfig.json is wrong. It should be:

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

    See the second example in this section of the documentation.