我正在尝试建立一个使用绝对路径而不是相对路径的简单typescript、node环境。
我按照这里的视频进行:https://www.youtube.com/watch?v=BKz7rnbQyK4,但是当我运行
注意:相对路径编译和工作正常。但是绝对路径会产生编译错误。
这里是我的.nvmrc:
这是我的 tsconfig.json 文件。
我按照这里的视频进行:https://www.youtube.com/watch?v=BKz7rnbQyK4,但是当我运行
npm run start:dev
时,无法正确解析绝对导入。VSCode智能提示可以很好地解析绝对导入路径,但是编译时会出现编译错误。注意:相对路径编译和工作正常。但是绝对路径会产生编译错误。
这里是我的.nvmrc:
v16.15.1
这是我的代码结构:
这是我的简单代码:
src/index.ts:
import add from '@src/math/add';
console.log(add(2, 1));
这里@src/math/add
出现编译错误。./math/add
可以正常编译。
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;
这里的@src/science/physics
出现了编译错误,但../science/physics
可以正常编译。
src/physics/force.ts:
const force = (mass: number, accelaration: number): number => mass * accelaration;
export default force;
这是我的 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
}
}
这是我的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"
}
}
最后,这是终端中的错误消息:
如果有人能帮我解决绝对路径的问题,我将非常感激。
谢谢