简体   繁体   中英

Cannot get the absolute paths working in typescript nodejs project

I am trying to setup a simple typescript, node environment with absolute paths instead of relative paths.

I followed the video here : but can't get the absolute imports to resolve properly when I run npm run start:dev . The VSCode intellisense is able to resolve the absolute import paths fine, but when I compile, I get compilation error.

Note: relative paths are compiling and working fine. But absolute paths are giving compilation error.

Here's my .nvmrc :

v16.15.1

Here is my code structure:

在此处输入图像描述

Here's my simple code:

src/index.ts:

import add from '@src/math/add';

console.log(add(2, 1));

Here @src/math/add is giving compilation error. ./math/add compiles fine.

src/math/add.ts:

import force from '@src/science/physics';
const add = (a: number, b: number): number => {
  console.log(`force:${force(5, 3)}`);
  return a + b;
};
export default add;

Here @src/science/physics is giving compilation error. ../science/physics compiles fine.

src/physics/force.ts:

const force = (mass: number, accelaration: number): number => mass * accelaration;

export default force;

Here is my tsconfig.json

{
  "ts-node": {
    "require": ["tsconfig-paths/register"],
    "esm": true,
    "experimentalSpecifierResolution": "node"
  },
  "exclude": ["node_modules", "dist", "coverage"],
  "include": ["src"],
  "compilerOptions": {
    "target": "ES2020",
    "lib": ["DOM", "ESNext"],
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,


    /* JavaScript Support */
    "allowJs": true,

    /* Emit */
    "outDir": "dist",
    "removeComments": true,

    /* Type Checking */
    "strict": true,
    "noImplicitAny": true,

    /* Modules */
    "module": "ES2020",
    "moduleResolution": "node",
    "rootDir": "." /*meaning wherever is this tsconfig.json file, that is the root directory*/,
    "baseUrl": ".",
    "paths": {
      "@src/*": ["src/*"]
    },

    /* Interop Constraints */
    "isolatedModules": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,

    /* Completeness */
    "skipLibCheck": true
  }
}

Here is my package.json :

{
  "type": "module",
  "name": "express-proj-setup-tut",
  "version": "1.0.0",
  "description": "",
  "main": "index.ts",
  "scripts": {
    "start:dev": "ts-node -r tsconfig-paths/register ./src/index.ts",
    "start:prod": "node -r ts-node/register/transpile-only -r tsconfig-paths/register ./dist/src/index.ts",
    "build": "tsc"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/node": "^18.7.9",
    "@typescript-eslint/eslint-plugin": "^5.33.1",
    "@typescript-eslint/parser": "^5.33.1",
    "eslint": "^8.22.0",
    "eslint-config-airbnb-base": "^15.0.0",
    "eslint-config-prettier": "^8.5.0",
    "eslint-import-resolver-typescript": "^3.4.2",
    "eslint-plugin-import": "^2.26.0",
    "eslint-plugin-prettier": "^4.2.1",
    "prettier": "^2.7.1",
    "ts-node": "^10.9.1",
    "tsconfig-paths": "^4.1.0",
    "typescript": "^4.7.4"
  }
}

Finally, here's the error message in terminal:

在此处输入图像描述

I would greatly appreciate if someone can help me out getting the absolute paths working.

thanks

I was unable to solve your issue with your configuration of module in package.json and module in tsconfig.json but if you remove "type": "module" from package.json and change to "module": "CommonJS" in your tsconfig.json you will be able to run "start:dev": "ts-node -r tsconfig-paths/register src/index.ts" .

For me output was

force:15
3

Related question: Can't run my Node.js Typescript project TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /app/src/App.ts

Check if your node.js version is higher than 14.6.0

Having ./src folder with ts code, ./dist folder as tsc output folder write following to map ./src as #root global path:

// tsconfig.json
{
  "compilerOptions": {
    ...
    "baseUrl": "./src",
    "paths": {
      "#root/*": [
        "./*"
      ]
    }
  }
}
// package.json
{
  ...
  "imports": {
    "#root/*": "./dist/*"
  },
}

Such aliases should start with # symbol.

Useful links:

In your tsconfig.json, you need change

"paths": {
      "@src/*": ["src/*"]
    },

for this:

"paths": {
      "@/*": [
        "src/*"
      ]
    },

And in include, you need add all paths that include ts files, like this:

"include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],

I hope that solve that compilation error:-)

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