Typescript absolute imports compatible with jest and AWS lambda

Elvis Ciotti
1 min readOct 11, 2023

--

If you don’t want paths to be relative (import { f } from ‘../../../lib/functions’) but absolute ( import { f } from ‘src/lib/functions’) , here is the config for Typescript 5.22 and jest 29.7 .I didnt’ find anywhere on the web explaining how to set up both ts and jest so I’m dropping here what worked for me.

tsconfig.json

{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"src/*": [
"./src/*"
],
}
}
}

in addition you can also define custom named directories in paths (e.g. @lib and then import with import … from ‘@lib’ ) but I want to keep the working example minimal.

jest.config.js

module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
roots: ['<rootDir>/src'],
"moduleNameMapper": {
"^src/(.*)$": [
"<rootDir>/src/$1"
],
}
// globalSetup: './src/jest-before-all.ts'
};

You can then use this in your code

import { f } from 'src/lib/functions'

IntelliJ immediately recognise the setting in case you refactor/move the code. In any case, a code replace would be very easy with absolute paths

AWS lambda handler

Since all your code will be present under the src directory into the output directory outDir setting), you’ll need to defined the AWS lambda handler as ./src/handler.functionName

Clap if useful.
Buy me a coffee if you found this useful.
Follow me for more.

--

--

Elvis Ciotti
Elvis Ciotti

Written by Elvis Ciotti

Software Contractor — Java, Spring, k8s, AWS, Javascript @ London - hire me at https://elvisciotti.github.io/

No responses yet