【问题标题】:Babel module resolver doesn't work as expected (node + typescript)Babel 模块解析器无法按预期工作(节点 + 打字稿)
【发布时间】:2021-06-13 14:20:04
【问题描述】:

在我的节点项目中,我使用 babel-plugin-module-resolver 来获得相对路径。

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"
        }
      }
    ] 
  ]
}

当我导入文件时,它不会显示任何错误。可以通过单击导入路径移动到特定文件。但是当它遵守时,它会给出以下错误。

如何解决这个问题??

【问题讨论】:

  • 您的 tsconfig “paths” 和 babel config “alias” 字段似乎不匹配。如果您在库文件夹中编辑 .babelrc 中的条目以添加 @,会发生什么情况? "@library": "./src/library", 只有从 @library 导入有问题,还是还有其他有问题的导入?
  • 关于ts-nodepaths的详细讨论请参见github.com/TypeStrong/ts-node/issues/138

标签: node.js typescript babeljs eslint babel-plugin-module-resolver


【解决方案1】:

看起来您的 TS 配置文件的 paths 和 Babel 配置文件的 alias 字段不匹配。正如@jered 在问题 cmets 中指出的那样,尝试在有问题的导入上添加 @ 前缀。

根据@pasi 所说,您还可以看到https://github.com/TypeStrong/ts-node/issues/138 进行关于ts-nodepaths 的长时间讨论。

【讨论】:

    猜你喜欢
    • 2023-03-17
    • 2018-07-30
    • 2021-08-19
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    • 2023-01-05
    • 2012-04-20
    • 2019-11-01
    相关资源
    最近更新 更多