nestjs如何在项目中配置路径别名

nestjs如何在项目中配置路径别名,nestjs,Nestjs,我在nestjs项目的tsconfig.json中配置了路径别名,但运行时出错 我试图像Angular那样进行配置,但在nestjs中出现了一个错误 这是我的tsconfig.json { "compilerOptions": { "module": "commonjs", "declaration": true, "removeComments": true, "emitDecoratorMetadata": true, "experimentalD

我在nestjs项目的tsconfig.json中配置了路径别名,但运行时出错

我试图像Angular那样进行配置,但在nestjs中出现了一个错误

这是我的tsconfig.json

{
  "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.json'
  • 添加“tsconfig path bootstrap.js”文件
  • //tsconfig-path-bootstrap.js
    const tsConfig=require('./tsConfig.json');
    const tsconfig路径=require('tsconfig-path');
    tsConfigPath.register({
    baseUrl:tsConfig.compilerOptions.outDir,
    路径:tsConfig.compilerOptions.path,
    });
    
  • 修改“nodemon.json”文件
  • 使用路径别名
  • 现在执行
    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';