javascript - typescript 不捆绑模块

标签 javascript node.js typescript amazon-web-services aws-cdk

我有一个 Node 应用程序,它将 typescript 文件编译到 dist 文件夹,然后通过 aws cdk 将这些文件用作 lambda 解析器。这是我的设置示例:

代码

register.ts

import ValidateUserFields from '../utils/forms';

exports.main = async function (event: any, context: any) {
    return {
      statusCode: 200,
    };
}

注册-lambda-config.ts

import { Construct } from 'constructs';
import * as apigateway from 'aws-cdk-lib/aws-apigateway';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as s3 from 'aws-cdk-lib/aws-s3';

export class FrontendService extends Construct {
  constructor(scope: Construct, id: string) {
    super(scope, id);

    const api = new apigateway.RestApi(this, 'frontend-api', {
      restApiName: 'Frontend Service',
      description: 'This service serves the frontend.',
    });

    const functionName = 'register';

    const handler = new lambda.Function(this, functionName, {
      functionName,
      runtime: lambda.Runtime.NODEJS_14_X,
      code: lambda.Code.fromAsset('dist/src/lambda'),
      handler: 'register.main',
    });

    const registerIntegration = new apigateway.LambdaIntegration(handler, {
      requestTemplates: { 'application/json': '{ "statusCode": "200" }' },
    });

    const registerResource = api.root.addResource('register');
    registerResource.addMethod('POST', registerIntegration);
  }
}

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2018",
    "module": "commonjs",
    "moduleResolution": "node",
    "lib": ["es2018"],
    "declaration": true,
    "strict": true,
    "noImplicitAny": false,
    "strictNullChecks": true,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "esModuleInterop": true,
    "noUnusedLocals": false,
    "noUnusedParameters": false,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": false,
    "inlineSourceMap": true,
    "inlineSources": true,
    "experimentalDecorators": true,
    "strictPropertyInitialization": false,
    "outDir": "dist",
    "typeRoots": ["./node_modules/@types"]
  },
  "exclude": ["node_modules", "cdk.out", "./dist/**/*"]
}

最后是我的 package.json 文件的脚本部分:

  "scripts": {
    "build": "tsc",
    "watch": "tsc -w",
    "cdk": "cdk",
    "bootstrap": "cdk bootstrap",
    "deploy": "cdk deploy && rimraf cdk.out",
    "destroy": "cdk destroy",
    "run-same-local-fe-api": "sam local start-api -p 4000 -t ./template.yaml",
    "dev": "npm run build && npm run synth && concurrently --kill-others \"npm run watch\" \"npm run run-same-local-fe-api\"",
    "synth": "cdk synth --no-staging > template.yaml"
  },

问题

当我运行 npm run dev 时,它会将我的 typescript 文件编译到 dist 文件夹,其结构与我在 src 中的结构相同文件夹(我所有的 typescript 文件所在的位置)。但是,如果我的 register.ts 文件中有任何导入,我会遇到以下错误:

{"errorType":"Runtime.ImportModuleError","errorMessage":"Error: Cannot find module '../utils/forms'\nRequire stack:\n- /var/task/register.js\n- /var/runtime/UserFunction.js\n- /var/runtime/index.js","stack":["Runtime.ImportModuleError: Error: Cannot find module '../utils/forms'","Require stack:","- /var/task/register.js","- /var/runtime/UserFunction.js","- /var/runtime/index.js"," at _loadUserApp (/var/runtime/UserFunction.js:202:13)"," at Object.module.exports.load (/var/runtime/UserFunction.js:242:17)","
at Object. (/var/runtime/index.js:43:30)"," at Module._compile (internal/modules/cjs/loader.js:1085:14)"," at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)"," at Module.load (internal/modules/cjs/loader.js:950:32)"," at Function.Module._load (internal/modules/cjs/loader.js:790:12)"," at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:75:12)"," at internal/main/run_main_module.js:17:47"]}

从相关本地文件(如上面代码中所示的“../utils/forms”)导入时会发生这种情况,从 node_modules 导入时也会发生这种情况。当我查看 dist 文件夹中已编译的 register.js 文件时,我发现它已尝试解析导入:

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const forms_1 = __importDefault(require("../utils/forms"));
const bucketName = process.env.BUCKET;

exports.main = async function (event, context) { ...

但是它显示上面的错误消息。我试过使用 require 而不是 import 但结果是一样的......

任何帮助将不胜感激!谢谢

最佳答案

表示如果没有minimal reproducible example,这真的很难回答;我至少会建议避免任何 requireexports,并且只使用 import/export 语句和以下在 tsconfig.json 中。

{
  "compilerOptions": {
    "module": "esnext"
  }
}

关于javascript - typescript 不捆绑模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71576645/

相关文章:

typescript - 如何防止 Firebase 一遍又一遍地创建同一个用户?

javascript - 想要控制我的动画的 FPS 是继续使用 setTimeout 而不是 requestAnimationFrame 的充分理由吗?

JavaScript 全局错误监听器不起作用

node.js - Azure Function App 对 Webhook 的初始响应

javascript - 正确捕获异步函数node.js

reactjs - namespace 声明不能位于与其合并的类或函数之前

javascript - 如何使用 Google map 查找当前位置(经度和纬度)?

javascript - 在 html 标签中打印 JavaScript 变量

asp.net - Nodejs 与 SignalR : why do we need server-side javascript?

typescript - Prisma + Nest JS,我应该使用什么 Promise 类型?