首页 > 解决方案 > 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;

paths在我tsconfig.json的 with中设置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: {
  extensions: ['.js', '.ts', '.tsx', '.jsx'],
  plugins: [new TsconfigPathsPlugin({ configFile: './tsconfig.json' })],
  alias: {
    Config: path.resolve(__dirname, 'config/', argv.mode)
  }
},

development.ts当我在这样的组件中导入文件时,我认为应该解决这个问题import config from 'Config';

但是我收到以下 TS 错误:

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

我没有看到我在这里做错了什么?

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

标签: typescriptwebpackimportaliasresolve

解决方案


推荐阅读