Search code examples
typescriptaws-lambdatsconfig

How to tell TypeScript compiler that this module is defined here?


I have this local TypeScript file, that when deployed, ends up in the /opt directory of my server. So if the file is located at layers/websocketapi/DataSender.ts locally, it gets deployed to opt/DataSender.js. However, as I am developing this project locally, it's not in my opt directory so Typescript complains that it can't find this module. However, if I change it to reference the local version, then my deployments break since it's no longer referencing the /opt directory where it is actually located on the server.

If I use a // @ts-ignore comment, the error goes away, but then I don't get the type support and it assumes a type of any.

Here is my code:

import { APIGatewayEvent } from 'aws-lambda';
// @ts-ignore
import DataSender from '/opt/DataSender';

export async function handler(event: APIGatewayEvent) {
  const dataSender = new DataSender();
  await dataSender.sendData(event.requestContext.connectionId!, { message: 'hi!' })
  return {
    statusCode: 200,
    body: 'Game created'
  }
}

How can I tell the Typescript compiler that this file I'm importing from the opt directory is actually located at layers/websocketapi/DataSender.js, but don't change the import statement?


Solution

  • You can add a paths mapping to your tsconfig.json file to map the import path /opt/* to the real path layers/websocketapi/*

    {
      "compilerOptions": {
        ...
        "baseUrl": ".",
        "paths": {
            "/opt/*": ["layers/websocketapi/*"]
        }
      }
      ...
    }
    

    Paths are resolved relative to baseUrl, more information about the path mapping can be found on the typescript documentation https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping