Typescript未绑定模块



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

代码

寄存器.ts

import ValidateUserFields from '../utils/forms';
exports.main = async function (event: any, context: any) {
return {
statusCode: 200,
};
}

注册lambda配置

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":"错误:无法查找模块'/utils/forms的\n必需堆栈:\n-/var/task/register.js\n-/var/runtime/UserFunction.js\n-/var/runtime/index.js"堆叠":[quot;Runtime.ImportModuleError:错误:找不到模块".."/utils/forms’"需要堆栈:"&quot-/"var/task/register.js"-/var/runtime/UserFunction.js"&quot-/var/runtime/index.js"在_loadUserApp(/var/runtime/UserFunction.js:22:13("在Object.module.exports.load(/var/runtime/UserFunction.js:242:17(">
在对象处。(/var/runtime/index.js:43:30("在模块_compile(internal/modules/cjs/loader.js:1085:14("在Object.Module_extensions..js(internal/modules/cjs/loader.js:1114:10("在Module.load(internal/modules/cjs/loader.js:950:32("位于Function.Module_load(internal/modules/cjs/loader.js:790:12("在Function.executeUserEntryPoint[作为runMain](internal/modules/run_main.js:75:12("在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,但结果是一样的。。。

如有任何帮助,我们将不胜感激!感谢

声明,如果没有最小的可复制示例,这真的很难回答;我至少建议避免使用任何requireexports,并且只使用import/export语句以及tsconfig.json.中的后续语句

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

嗯。。我确实理解你希望你的主要功能看起来像这样:

// final result written in javascript
exports.main = async function (event, context) {
return {
statusCode: 200,
};
}

但是。。。在CCD_ 15中使用CCD_。相反,Typescript使用export指令(末尾没有s(来定义应该导出代码的哪些部分。然后由您的tsconfig.json文件来确定将使用哪种语法来表示此导出(这实际上是Typescript引擎的一部分(

所以。。。在Typescript 中这样写的脚本

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

将在Typescript中解析如下(我已经使用module: commonjs实现了以下结果(

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.main = void 0;
async function main(event, context) {
return {
statusCode: 200,
};
}
exports.main = main;
//# sourceMappingURL=test.js.map

请注意生成的js file如何按照您的预期正确使用modile.exportsmain

简而言之:使用Typescript时,请使用语言指令,并让引擎为您完成其余操作。通过这种方式,可以为不同的环境部署单个代码源,而无需更改应用程序逻辑。整洁的

最新更新