juanjoDiaz / serverless-middleware

Serverless plugin to allow middleware handlers configured directly in serverless.yaml
MIT License
18 stars 11 forks source link

ERR_MODULE_NOT_FOUND when using Typescript and targeting ES6 or higher #45

Closed AlexAVL closed 1 year ago

AlexAVL commented 1 year ago

Node supports require without an extension, but does not support import without an extension. The built middleware files all have no extension on the imports. This is fine when they're compiled to an ES5 target because they are rewritten to requires, but when targeting ES6 they are not rewritten and remain without an extension. This means running a function in Serverless throws a ERR_MODULE_NOT_FOUND.

My tsconfig.json looks like this:

{
  "compilerOptions": {
    "esModuleInterop": true,
    "preserveConstEnums": true,
    "strictNullChecks": true,
    "sourceMap": true,
    "allowJs": true,
    "target": "es6",
    "outDir": ".build",
    "moduleResolution": "node",
    "lib": ["es2021"],
    "rootDir": "./",
    "forceConsistentCasingInFileNames": true,
    "noImplicitReturns": true,
    "strict": true,
    "noUnusedLocals": true
  }
}

And Serverless is targetting nodejs18.x.

It seems that adding .js in the import template path in /src/typescript.js:26 solves this. It may also need adding to /src/javascript.js:26. I'm not sure if this will cause more problems than it solves if people are importing non-js files here (which they shouldn't be as middleware), but changing this line makes everything work for me.

juanjoDiaz commented 1 year ago

Thanks for reporting! I'll submit a fix asap

juanjoDiaz commented 1 year ago

Fixed in version 3.2.0