Babel module resolver doesn't work as expected (node + typescript)

2.2k views Asked by At

In my node project, I use babel-plugin-module-resolver to have relative paths.

tsconfig.json

{
  "compilerOptions": {
    "outDir": "build",
    "target": "es5",                          
    "module": "commonjs",                     
    "strict": true,     
    "noEmit": true,                    
    "esModuleInterop": true,                 
    "skipLibCheck": true,                    
    "forceConsistentCasingInFileNames": true,  
    "baseUrl": "./src",
    "paths": {
      "constants/*": ["constants/*"],
      "data/*": ["data/*"],
      "database/*": ["database/*"],
      "enums/*": ["enums/*"],
      "features/*": ["features/*"],
      "@library/*": ["library/*"],
    }
  }
}

.eslintrc

{
  "parser": "@typescript-eslint/parser",
  "extends": ["plugin:@typescript-eslint/recommended"],
  "parserOptions": {
    "ecmaVersion": 2018,
    "sourceType": "module"
  },
  "settings": {
    "import/resolver": {
      "babel-module": {}
    }
  },
  "rules": {
    "semi": ["warn", "always"],
    "quotes": ["warn", "single"],
    "max-len": ["warn", 150],
    "no-console": 1,
    "@typescript-eslint/explicit-function-return-type": "off",
    "@typescript-eslint/no-explicit-any": 0,
    "@typescript-eslint/no-inferrable-types": [
      "warn", {
        "ignoreParameters": true
      }
    ]
  }
}

.babelrc

{
  "presets": [
    "@babel/preset-typescript",
    "@babel/preset-env"
  ],
  "plugins": [ 
    [
      "module-resolver",
      {
        "alias": {
          "config": "./src/config",
          "constants": "./src/constants",
          "data": "./src/data",
          "enums": "./src/enums",
          "features": "./src/features",
          "library": "./src/library",
          "middleware": "./src/middleware",
          "utils": "./src/utils"
        }
      }
    ] 
  ]
}

when I import files, it doesn't display any errors. Can move to the specific file by clicking on the import path. But when it complies, it give the following error.enter image description here

how to fix this issue??

1

There are 1 answers

0
Andrei Jiroh Eugenio Halili On

Looks like your TS config file's paths and Babel config file's alias fields don't match. Try prefixing @ on your problematic imports, as what @jered pointed out in the question comments.

You may also see https://github.com/TypeStrong/ts-node/issues/138 for the long discussion regarding ts-node and paths, as per @pasi said.