网站搜索

Typescript 无法解析声明为 webpack 别名的模块


我已设置好我的 webpack 配置,以解析 development 或 production 的配置文件。

文件夹结构如下:

Project
 |    
 +-- config
   |  
    +-- development.ts
    +-- production.ts

配置文件只是作为默认导出的一种对象:

const config = {
  errorUrl: 'http://localhost:3000/error',
  successUrl: 'http://localhost:3000',
  branch: 'Branch',
  tag: 'Tag1',
  username: 'Demo client DEV',
  debug: true,
};

export default config;

我在 tsconfig.json 中设置了 paths,并将 baseUrl 设置为项目根目录 .:

{
  "compilerOptions": {
    "baseUrl": ".",
    "outDir": "build",
    "paths": {
      "@/pages/*": ["src/pages/*"],
      "@/components/*": ["src/components/*"],
      "Config": ["config/*"]
    },
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "checkJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": false,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve"
  },
  "include": ["**/*.ts", "**/*.tsx"],
  "exclude": [
    "node_modules",
    "dist",
    "coverage",
    "functional-test",
    "webpack.config.js",
    "jest.config.js",
    "**/*.spec.ts",
    "**/*.spec.tsx"
  ],
  "typeAcquisition": {
    "include": ["jest"]
  }
}

我在 webpack.config 中添加了 resolve:

resolve: {
  extensions: ['.js', '.ts', '.tsx', '.jsx'],
  plugins: [new TsconfigPathsPlugin({ configFile: './tsconfig.json' })],
  alias: {
    Config: path.resolve(__dirname, 'config/', argv.mode)
  }
},

我原以为当我在组件中像这样导入文件 import config from 'Config'; 时,它应该能解析 development.ts

但是我得到了以下 TS 错误:

TS2307: Cannot find module 'Config' or its corresponding type declarations.

我不明白我在这里做错了什么?

当我 console.log(path.resolve(__dirname, 'config/')); 时,它似乎也是正确的路径,所以不确定为什么它没有解析。