简体   繁体   中英

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

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. 在此处输入图像描述

how to fix this issue??

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM