Home > Enterprise >  typescript 4.4.4: tsconfig paths not resolving as expected
typescript 4.4.4: tsconfig paths not resolving as expected

Time:10-22

my tsconfig.json

{
  "compilerOptions": {
    "target": "ES2018",
    "module": "CommonJS",
    "lib": ["ESNext", "ESNext.AsyncIterable"],
    "skipLibCheck": true,
    "sourceMap": true,
    "outDir": "./dist",
    "moduleResolution": "node",
    "removeComments": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "resolveJsonModule": true,
    "baseUrl": "./",
    "paths": {
      "@/*": ["src/*"],
      "@config": ["src/config"],
    }
  },
  "exclude": ["node_modules"],
  "include": ["./src/**/*.ts"]
}

I am pretty sure there is nothing wrong in tsconfig paths because I even get path autocompletion from my IDE. however when my code is compiled (tsc --project tsconfig.json)

import { PRODUCTION } from '@config';

// or

import { PRODUCTION } from '@/config';

I get following javascript

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const _config_1 = require("@config");
console.log(_config_1.PRODUCTION);
//# sourceMappingURL=index.js.map

but javascript doesn't understand what "@" is therefore I get "module not found" error. How can I solve this problem?

CodePudding user response:

See this issue on TypeScript's GitHub project: Module path maps are not resolved in emitted code (#10866)

tl;dr

  • TypeScript won't rewrite your module paths
  • paths was designed to help TypeScript understand path aliases used by bundlers
  • You'll either need to:
    • use a bundler, such as webpack, and configure its own path maps
    • use a build time tool, such as tspath, to rewrite the paths
    • modify the runtime module resolver, with something like module-alias
  • Related