ESLint encountering a "Module path unresolved" issue in conjunction with SAM Serverless Monorepo

In the process of developing a basic Hello World function for AWS Lambda/APIGateway, I aim to integrate ESLint and Typescript features. Typically, when working with Typescript and ESlint, inclusion of the eslint-plugin-import package and specifying the extensions in my .eslintrc file is required:

  "settings": {
    "import/resolver": {
      "node": {
        "extensions": [".js", ".jsx", ".ts", ".tsx"]
      }
    }
  }

In this particular monorepo setup, despite having these configurations in place, I still encounter the

Unable to resolve path to module 'aws-lambda'
error. Here's how my repository is structured:

apis/
    users/
        dist/ <-- My compiled JS code
        node_modules/
        src/
            functions/ <-- My Typescript Lambda functions
        test/ <-- My Jest tests
        .eslintrc <-- My ESLint config
        package.json
        template.yaml <-- My SAM template
        tsconfig.json <-- My Typescript config
        webpack.config.js <-- My WebPack config

Below is the content of my .eslintrc file:

{
  "root": true,
  "env": {
    "es2020": true,
    "mongo": true,
    "node": true,
    "jest": true
  },
  "parser": "@typescript-eslint/parser",
  "extends": [
    "airbnb",
    "plugin:@typescript-eslint/recommended",
    "plugin:prettier/recommended" // This will display prettier errors as ESLint errors. Make sure this is always the last configuration.
  ],
  "ignorePatterns": ["dist/", "coverage/", "test/"],
  "parserOptions": {
    "ecmaVersion": 2018,
    "sourceType": "module",
    "ecmaFeatures": {
      "impliedStrict": true
    }
  },
  "rules": {
    "import/extensions": [
      "error",
      "ignorePackages",
      {
        "js": "never",
        "jsx": "never",
        "ts": "never",
        "tsx": "never"
      }
    ],
    "max-len": [
      "error",
      {
        "code": 100,
        "ignoreComments": true,
        "ignoreStrings": true,
        "ignoreTemplateLiterals": true
      }
    ],
    "quotes": ["error", "single", { "allowTemplateLiterals": true }],
    "no-unused-vars": "off",
    "@typescript-eslint/no-unused-vars": [
      "error",
      {
        "vars": "all",
        "args": "none"
      }
    ]
  },
  "settings": {
    "import/resolver": {
      "node": {
        "extensions": [".js", ".jsx", ".ts", ".tsx"]
      }
    }
  }
}

This snippet showcases my tsconfig.json settings:

{
  "compilerOptions": {
    "module": "commonjs",
    "esModuleInterop": true,
    "target": "esnext",
    "noImplicitAny": true,
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "dist"
  },
  "include": ["src/**/*"],
  "exclude": ["**/*.test.*"]
}

Last but not least, here is my webpack configuration:

/* eslint-disable */
const path = require('path');
const { readFileSync } = require('fs');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const { yamlParse } = require('yaml-cfn');
/* eslint-enable */

const conf = {
  prodMode: process.env.NODE_ENV === 'production',
  templatePath: './template.yaml',
};

const cfn = yamlParse(readFileSync(conf.templatePath));
const entries = Object.values(cfn.Resources)

  // Find nodejs functions
  .filter((resource) => resource.Type === 'AWS::Serverless::Function')
  .filter(
    (resource) =>
      (resource.Properties.Runtime && resource.Properties.Runtime.startsWith('nodejs')) ||
      (!resource.Properties.Runtime && cfn.Globals.Function.Runtime)
  )
  .map((resource) => ({
    // Isolate handler src filename
    handlerFile: resource.Properties.Handler.split('.')[0],
    // Build handler dst path
    CodeUriDir: resource.Properties.CodeUri.split('/').splice(1).join('/')
  }))
  .reduce(
    (resources, resource) =>
      Object.assign(
        resources,
        // Generate {outputPath: inputPath} object
        { [`${resource.CodeUriDir}/${resource.handlerFile}`]: `./src/${resource.CodeUriDir}.ts` }
      ),
    {}
  );

module.exports = {
  entry: entries,
  target: 'node',
  mode: conf.prodMode ? 'production' : 'development',
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader'
      }
    ]
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js']
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js',
    libraryTarget: 'commonjs2'
  },
  devtool: 'source-map',
  plugins: conf.prodMode
    ? [
        new UglifyJsPlugin({
          parallel: true,
          extractComments: true,
          sourceMap: true
        })
      ]
    : []
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Getting the PlayerId after a user subscribes in OneSignal with Ionic2

Currently working on an app with Ionic2 and facing a challenge with retrieving the player id after a user subscribes in order to store it in my database. Any suggestions on how I can retrieve the unique player id of OneSignal users post-subscription? ...

You are unable to link to <custom directive selector> because it is not recognized as a valid property of 'div'

I am currently working on a project in StackBlitz, and you can find the link here: https://stackblitz.com/edit/angular-fxfo3f?file=src/directives/smooth-height.directive.ts I encountered an issue: Error in src/components/parent/parent.component.html (2:6) ...

The system encountered a TypeError: Unable to access the 'nativeElement' property as it is undefined

Hello, I am a beginner in Angular 2 and currently working on an image cropping plugin. My goal is to display the image on a canvas element. Below is my HTML code: <div class="row"> <div class="col-sm-6"> <canvas id="layout" width="40 ...

Array that provides specific data types for indexes

Could be a tricky question or maybe not feasible, but I've been scratching my head over it for quite some time and just can't seem to crack it. Appreciate any help! The T generic creates a union type: const arrayToArray = <T>(values: T[]) ...

Numerous unspecified generic arguments

Imagine a collection of functions, each capable of taking an argument and returning a value (the specifics don't matter): function convertToNumber(input: string): number { return parseInt(input) } function convertToBoolean(input: number): boolean { ...

Posting an array as form data in Angular Typescript: A step-by-step guide

Hello there, I'm currently developing an application using Angular 8 and integrating web.api within .net core 2.2. One of the challenges I encountered is dealing with multi-selectable checkboxes in a form that also includes "regular" inputs and file ...

Listening for combinations of keys pressed using HostListener

I've been attempting to detect when a user presses the Shift+Tab key combination on the keyboard, but for some reason I can't get the event to trigger. @HostListener('keyup', ['$event']) @HostListener('keydown', [&a ...

Bringing a JavaScript function into a TypeScript file results in it being treated as a namespace

Trying to bring a vanilla JavaScript function into a TypeScript file within a React Native app has presented some challenges. The import process goes smoothly when working with JS, but switching to TS triggers the error message: Cannot use namespace &apos ...

Group multiple typescript files into separate outFile modules

Can TypeScript files be grouped into multiple outFiles? I want to bundle my Typescript code, but instead of one single JS file, I would like to organize my TS into separate JS files such as controllers.js and plugins.js. The options in the TypeScript pro ...

Generating a dynamic SQL Insert statement based on an array object

I am currently working on a Typescript project where I am looking to optimize my Insert function by creating one Insert statement for all the elements in an object, rather than generating multiple Inserts for each array item. Here is the code snippet of m ...

Sending a message through Discord.JS to a designated channel

Recently diving into Discord.JS, I am struggling to understand how to make my bot send a message to the General Chat when a new user joins. Many examples I've come across suggest using the following code: const channel = client.channels.cache.find(ch ...

Traversing an array of objects in TypeScript and appending to a separate array if not already present

I have been given an array containing objects in the following format: export interface Part { workOrder?: string; task?: string; partNumber?: string; qty?: number; image?: string; name?: string; } My goal is to loop through each object in th ...

Creating components with the viewContainerRef in Angular2 is functioning as expected

When attempting to load a dynamic component into the root component using viewContainerRef.createComponent, I encountered an issue where it appended to the wrong place. https://i.stack.imgur.com/lF1yT.png Here is my code: -----app.compoment.ts----- exp ...

Angular is unable to start the variable_INITIALIZation process

I've created a method called get that returns data of type ProductModel. getProduct(id:number): Observable<ProductModel[]> { const url = `${'api/product/getProductById/'}/${id}`; return this.http.get<ProductModel[]>(u ...

What is the best way to apply multiple array filters to an object list in react.js?

Looking to filter an array of items using multiple filter arrays in order to display only the items that match all selected filters. For example: The main array contains a table with the following data: ID TypeID LocationID Name 1 2 ...

Can you guide me on how to specify the return type in NestJS for the Session User in a request?

async authenticated(@Req() request: Request) { const user = request.user return user } It is important for the 'user' variable to have the correct type globally. While working with express passport, I came across the following: decl ...

What is the best way to link multiple select tags in an HTML document?

I am working with a data grid that contains student information such as Name, Class, and Score. Each row has a checkbox for selection. The requirement is that when the user selects one or more rows and clicks on the "show information" Button, a new windo ...

The term 'shuterstock_init' is meant to be a type, however, it is mistakenly being treated as a value in this context

I am working on a service called class imageService, which mainly consists of key value pairs export type servicesName = "unsplash" | "pexels" | "pixabay" | 'shutterstock'; export type Service = { [key in services ...

Is there a way to automatically scroll 50 pixels down the page after pressing a button?

Is there a way to make my page scroll down in Angular when a button is clicked? I attempted to use this code, but it didn't have the desired effect. What is the best method for scrolling the page down by 50px? window.scrollBy(0, 50); ...

Angular 2: Integrating a service into a class

I am working on an Angular class that represents a shape. My goal is to be able to create multiple instances of this class using a constructor. The constructor requires several arguments that define the properties of the shape. constructor(public center: ...