cdk合成器:尝试从相对路径导入切换到绝对路径导入时找不到模块

Yan*_*Liu 1 typescript aws-cdk

我正在将 CDK 包的相对路径导入切换为绝对路径导入,并在运行时出现此错误cdk synth

$ cdk synth
Error: Cannot find module 'lib/CodePipelineStack'
Run Code Online (Sandbox Code Playgroud)

我按照此方法使用打字稿中的绝对路径进行导入以设置文件中的baseUrl和。pathstsconfig.json

不知道为什么它不起作用。

更多背景信息

我的项目结构如下所示:

在此输入图像描述

我的 tsconfig.json 是:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "bin/*": [ "./bin/*" ],
      "lib/*": [ "./lib/*" ],
      "test/*": [ "./test/*" ]
    },
    "target": "ES2018",
    "module": "commonjs",
    "lib": [
      "es2018"
    ],
    "declaration": true,
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "noUnusedLocals": false,
    "noUnusedParameters": false,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": false,
    "inlineSourceMap": true,
    "inlineSources": true,
    "experimentalDecorators": true,
    "strictPropertyInitialization": false,
    "typeRoots": [
      "./node_modules/@types"
    ]
  },
  "exclude": [
    "node_modules",
    "cdk.out"
  ]
}
Run Code Online (Sandbox Code Playgroud)

我尝试"baseUrl": "./""baseUrl": ".",两者都不起作用。

skl*_*lnd 6

cdk 合成器ts-node在幕后使用。ts-node需要额外的包 ( tsconfig-paths) 和一些额外的配置来根据您的paths配置加载模块tsconfig.json

{
  "ts-node": {
    "require": ["tsconfig-paths/register"]
  }
}
Run Code Online (Sandbox Code Playgroud)

更多文档: https: //github.com/TypeStrong/ts-node#paths-and-baseurl

你的最终结果tsconfig.json将如下所示:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "bin/*": [ "./bin/*" ],
      "lib/*": [ "./lib/*" ],
      "test/*": [ "./test/*" ]
    },
    "target": "ES2018",
    "module": "commonjs",
    "lib": [
      "es2018"
    ],
    "declaration": true,
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "noUnusedLocals": false,
    "noUnusedParameters": false,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": false,
    "inlineSourceMap": true,
    "inlineSources": true,
    "experimentalDecorators": true,
    "strictPropertyInitialization": false,
    "typeRoots": [
      "./node_modules/@types"
    ]
  },
  "exclude": [
    "node_modules",
    "cdk.out"
  ], 
  "ts-node": {
    "require": ["tsconfig-paths/register"]
  }
}
Run Code Online (Sandbox Code Playgroud)