无服务器框架无法识别 tsconfig 的路径

Tom*_*eck 5 node.js aws-lambda serverless-framework tsconfig-paths

我正在尝试使用无服务器框架将 Node.js 应用程序部署到 Lambda,但是,我的 Node 代码使用 tsconfig.json 中的路径来引用导入,但无服务器部署过程失败。如何连接 serverless.yml 来确认并使用 tsconfig.json 中定义的路径?

我已经安装了 serverless-plugin-typescript,但它似乎无法识别 tsconfig 中的路径。

无服务器.yml

service:
  name: app-name

custom:
  webpack:
    webpackConfig: ./webpack.config.js
    includeModules: true

plugins:
  - serverless-webpack
  - serverless-plugin-typescript

...
Run Code Online (Sandbox Code Playgroud)

tsconfig.ts

{
  "compileOnSave": true,
  "compilerOptions": {
    "lib": [
      "es2017"
    ],
    "baseUrl": "./src",
    "declaration": true,
    "downlevelIteration": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "outDir": "./dist",
    "paths": {
      "@config/*": [
        "config/*"
      ],
      "@core/*": [
        "core/*"
      ],
      "@infra/*": [
        "infra/*"
      ],
      "@modules/*": [
        "modules/*"
      ],
      "@shared/*": [
        "shared/*"
      ]
    },
    "preserveConstEnums": true,
    "removeComments": true,
    "rootDir": "./src",
    "skipLibCheck": true,
    "sourceMap": true,
    "strict": true,
    "strictNullChecks": false,
    "target": "es2017",
    "typeRoots": [
      "node_modules/@types"
    ],
    "types": [
      "node"
    ]
  },
  "include": [
    "./**/*.ts"
  ],
  "exclude": [
    "node_modules/**/*",
    ".serverless/**/*",
    ".webpack/**/*",
    "_warmup/**/*",
    ".vscode/**/*"
  ]
}
Run Code Online (Sandbox Code Playgroud)

Tom*_*eck 5

我找到了答案。事实证明您需要安装tsconfig-paths-webpack-plugin。然后在 webpack.config.js 中添加以下内容:

npm install --save-dev tsconfig-paths-webpack-plugin
Run Code Online (Sandbox Code Playgroud)

在 webpack.config.js 中:

const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');


module.exports = {
  ...
  resolve: {
    plugins: [new TsconfigPathsPlugin({ configFile: "./tsconfig.json" })]
  },
  ...
};
Run Code Online (Sandbox Code Playgroud)

注意:请务必使用解析部分内的插件。根目录中有一个插件,但是,TsconfigPathsPlugin只能在resolve/plugins 中工作。

如果您遇到同样的问题,我希望这对您有所帮助。