Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to set up Typescript in Lambda function #11551

Closed
klaeuiM opened this issue Dec 7, 2022 · 9 comments
Closed

How to set up Typescript in Lambda function #11551

klaeuiM opened this issue Dec 7, 2022 · 9 comments
Labels
functions Issues tied to the functions category pending-triage Issue is pending triage question General question

Comments

@klaeuiM
Copy link

klaeuiM commented Dec 7, 2022

Amplify CLI Version

10.5.1

Question

I'm trying to set up a Typescript lambda function by following these instructions https://docs.amplify.aws/cli/function/build-options/, but keep getting errors. As alternatives, I looked at issues 9113, 8668, 6398, 659, and 6414, all of which is rather confusing and appears to boil down to the instructions being wrong.

My folder structure is

     .gitignore
     tsconfig.json
     /src
        package.json
     /ts
        index.ts
        event.json

.gitignore
/src/*

tsconfig.json
{ "compilerOptions": { "allowSyntheticDefaultImports": true, "esModuleInterop": true, "lib": [ "dom", "esnext" ], "module": "commonjs", "moduleResolution": "node", "noUnusedLocals": true, "noUnusedParameters": true, "skipLibCheck": true, "resolveJsonModule": true, "typeRoots": [ "./src/node_modules/@types" ], "outDir": "./src", "baseUrl": "./", "rootDir": "./ts", "paths": { "src": [ "./ts" ] } } }

package.json
{ "name": "econapploadindustrialproduction", "version": "2.0.0", "description": "Lambda function generated by Amplify", "main": "index.js", "license": "Apache-2.0", "devDependencies": { "@types/aws-lambda": "^8.10.92", "typescript": "^4.9.3" }, "dependencies": { "csv-parse": "^5.3.3" } }

index.ts
`import type { APIGatewayProxyHandler } from 'aws-lambda';
import { version } from 'node:process'

export const handler: APIGatewayProxyHandler = async (event, _context) => {
console.log(EVENT: ${JSON.stringify(event)});
console.log(NodeJS Version: ${version});

return {
    statusCode: 200,
    //  Uncomment below to enable CORS requests
    //  headers: {
    //      "Access-Control-Allow-Origin": "*",
    //      "Access-Control-Allow-Headers": "*"
    //  }, 
    body: JSON.stringify('Hello from Lambda!!!'),
};

};`

I added "amplify:econappLoadIndustrialProduction": "cd amplify/backend/function/econappLoadIndustrialProduction && tsc -p ./tsconfig.json" to the project package.json (I left out the trailing cd - as it causes an error).

Upon amplify push, I get these errors:

  • ts/index.ts(8,45): error TS2307: Cannot find module 'aws-lambda' or its corresponding type declarations.
  • ts/index.ts(10,25): error TS2307: Cannot find module 'node:process' or its corresponding type declarations.

So is the documentation wrong? If so, what is the recommended way because the above-mentioned discussions are all over the place. I'm not familiar with CDK; ought I be using that instead?

Secondly, what is the recommended way to import API.ts and the graphql functions from the project folder into the lambda folder?

Any help is very much appreciated.

@klaeuiM klaeuiM added pending-triage Issue is pending triage question General question labels Dec 7, 2022
@josefaidt josefaidt added the functions Issues tied to the functions category label Dec 7, 2022
@josefaidt
Copy link
Contributor

Hey @klaeuiM 👋 thanks for raising this! Do you have the corresponding @types/node and @types/aws-lambda packages installed? If so, it is possible the types are not found as node_modules are installed in the defined outdir (src). Can you try manually pointing types to src/node_modules/?

So is the documentation wrong? If so, what is the recommended way because the above-mentioned discussions are all over the place. I'm not familiar with CDK; ought I be using that instead?

I do think the documentation here is confusing, however the TypeScript support for functions can definitely be improved.

Secondly, what is the recommended way to import API.ts and the graphql functions from the project folder into the lambda folder?

This experience can also be improved. In the meantime you can use a command hook to manually copy these files to your funciton's directory after they are updated.

For what it's worth when creating functions with Amplify everything in the src directory will be zipped and that archive is placed in dist. What is needed for the function to run should be accessible from within src. It is possible to write functions elsewhere in the project and output the bundle to amplify/backend/function/<function-name>/src, or also manually copy the package.json and lockfile if you need external dependencies.

@josefaidt josefaidt added the pending-response Issue is pending response from the issue author label Dec 7, 2022
@klaeuiM
Copy link
Author

klaeuiM commented Dec 7, 2022

Thanks! I was missing the node types. Regarding aws-lambda, this works:

import type { APIGatewayProxyHandler } from '../src/node_modules/@types/aws-lambda';

but this does not:

import type { APIGatewayProxyHandler } from 'aws-lambda';

Update: when I run amplify push the types in the function node_modules get erased. However, that I was able to fix by moving the @types from the devDependencies to the dependencies

@github-actions github-actions bot removed the pending-response Issue is pending response from the issue author label Dec 7, 2022
@josefaidt
Copy link
Contributor

Ah @klaeuiM I believe what is happening is the function's build command is running after the CLI installs production dependencies, which is why those are missing on push and the build. As a workaround, can you remove the npm script in favor of using a pre-push.sh command hook to build your TypeScript function?

@josefaidt josefaidt added the pending-response Issue is pending response from the issue author label Dec 7, 2022
@klaeuiM
Copy link
Author

klaeuiM commented Dec 7, 2022

I think that the function package.json / node_modules is being ignored because it is in a sister folder (src) of the ts folder; instead, the import resolves to the project package.json / node_modules: When I add @types/aws-lambda to the project dependencies, the import works

I tried to address this by including typeRoots in the tsconfig file, but it appears that statement gets ignored.

@github-actions github-actions bot removed the pending-response Issue is pending response from the issue author label Dec 7, 2022
@josefaidt
Copy link
Contributor

Yes, and I've added this issue to our "Function build redesign" project board to track alongside our work to improve the function category and subsequently TypeScript support. Instead of the npm script were you able to execute the build with a pre-push hook?

"amplify:econappLoadIndustrialProduction": "cd amplify/backend/function/econappLoadIndustrialProduction && tsc -p ./tsconfig.json"

@josefaidt josefaidt added the pending-response Issue is pending response from the issue author label Dec 7, 2022
@klaeuiM
Copy link
Author

klaeuiM commented Dec 8, 2022

I have not used hooks before and I use Windows; I get a "Hooks runtime not found: Bash" error message.

But this misses the point that in this setup with parallel directories the imports cannot access the function node_modules. To address that I successfully made these changes:

  • moved all files from the /ts folder to the /src folder and eliminated the /ts folder
  • moved tsconfig.json into the src folder
  • changed the .gitignore file to:

/src/*.js /src/node_modules/*

  • changed tsconfig.json to (ie, removed outDir, baseUrl, rootDir, paths; added exclude):

{ "compilerOptions": { "allowSyntheticDefaultImports": true, "esModuleInterop": true, "lib": [ "dom", "esnext" ], "module": "commonjs", "moduleResolution": "node", "noUnusedLocals": true, "noUnusedParameters": true, "skipLibCheck": true, "resolveJsonModule": true, }, "exclude": [ "src/node_modules", "src/**/*.spec.ts" ] }

  • changed the script in the project package.json to (ie, pointed it to the src directory):

"amplify:econappLoadIndustrialProduction": "cd amplify/backend/function/econappLoadIndustrialProduction/src && tsc -p ./tsconfig.json"

This setup may have the added advantage that something like the following actually works (whether that's a good idea I don't know yet, but probably worth pursuing):

import type * as API from '../../../../../src/API';

The issue with the deleted types I solved by moving them into the production dependencies.

Obviously the src is a jumble of stuff that really does not belong into a src folder, but that was already the base case--just adding to it.

@github-actions github-actions bot removed the pending-response Issue is pending response from the issue author label Dec 8, 2022
@klaeuiM
Copy link
Author

klaeuiM commented Dec 8, 2022

Unrelated to that, do you happen to know how to get amplify mock function to use a node version other than v14.18.1? I have v18.12.1 installed on my computer and the cloudformation template for the function is set to runtime nodejs18.x

@josefaidt
Copy link
Contributor

Hey @klaeuiM

Unrelated to that, do you happen to know how to get amplify mock function to use a node version other than v14.18.1? I have v18.12.1 installed on my computer and the cloudformation template for the function is set to runtime nodejs18.x

This behavior is currently documented as a feature request #10940, where the CLI is using the version of Node it is built with rather than the Node executable found on your system.

Glad to hear you found a suitable workaround!

@josefaidt josefaidt added the pending-response Issue is pending response from the issue author label Dec 8, 2022
@klaeuiM
Copy link
Author

klaeuiM commented Dec 8, 2022

Thanks! I appreciate the help

@klaeuiM klaeuiM closed this as completed Dec 8, 2022
@github-actions github-actions bot removed the pending-response Issue is pending response from the issue author label Dec 8, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
functions Issues tied to the functions category pending-triage Issue is pending triage question General question
Projects
None yet
Development

No branches or pull requests

2 participants