nestjs如何在项目中配置路径别名
我在nestjs项目的tsconfig.json中配置了路径别名,但运行时出错 我试图像Angular那样进行配置,但在nestjs中出现了一个错误 这是我的tsconfig.jsonnestjs如何在项目中配置路径别名,nestjs,Nestjs,我在nestjs项目的tsconfig.json中配置了路径别名,但运行时出错 我试图像Angular那样进行配置,但在nestjs中出现了一个错误 这是我的tsconfig.json { "compilerOptions": { "module": "commonjs", "declaration": true, "removeComments": true, "emitDecoratorMetadata": true, "experimentalD
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es6",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"paths": {
"~auth/*": ["src/auth/*"]
}
},
"exclude": ["node_modules"]
}
像这样使用它
import { userLoginJwt } from '~auth/jwt-names'
启动错误
$ npm run start:dev
[0] internal/modules/cjs/loader.js:584
[0] throw err;
[0] ^
[0]
[0] Error: Cannot find module 'src/auth/jwt-names'
抱歉,我在此强调运行
npm run start
可以正常工作,但运行npm run start:dev
可能会导致意外情况。src
在编译后不可用,因为所有代码都会移动到dist
文件夹。相反,您应该在tsconfig
中设置一个baseUrl
指向src
和outDir
指向dist
然后从路径中删除src
。我还建议阅读Typescript路径映射,以便更好地了解正在发生的事情。这项工作,我的工作是:
//tsconfig-path-bootstrap.js
const tsConfig=require('./tsConfig.json');
const tsconfig路径=require('tsconfig-path');
tsConfigPath.register({
baseUrl:tsConfig.compilerOptions.outDir,
路径:tsConfig.compilerOptions.path,
});
npm运行start:dev
错误已消失
package.json
“start:dev”:“nest start--watch--exec'node-r tsconfig path/register-r ts node/register./src/main.ts'
npm运行开始:dev
Nestjs已经更新了模板,上面的代码在新版本中不起作用。对于新版本,直接在
tsconfig.json
中设置paths
字段。这是一个很好的一般建议,但NestJS似乎会强制您对baseURL使用“/”,因此这不是一个选项
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es6",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./src",
"incremental": true,
"paths": {
"~auth/*": ["auth/*"]
}
},
"exclude": ["node_modules"]
}
{
"watch": ["dist"],
"ext": "js",
"exec": "node -r ./tsconfig-paths-bootstrap.js dist/main.js"
}
import { userLoginJwt } from '~auth/jwt-names';