serverless / typescript

TypeScript definitions for Serverless Framework service configuration
141 stars 25 forks source link

Import / Export in serverless.ts when targeting ES module in tsconfig #37

Closed cohlar closed 3 years ago

cohlar commented 3 years ago

Hello,

This is more of a TypeScript issue than a Serverless issue, however I believe it may be useful to future Serverless TS users so I hope it's fine to ask here.

I have been using Serverless for a few months, and it's been working great, I built all by "backend" and "job server" with it. Now I want to add a Vue.js frontend in the same repo, which requires to set "module": "esnext" in tsconfig.json (well technically it's not "required", but I would prefer it that way). My issue is that I am no longer able to import my handlers / export my serverless configuration in serverless.ts - I get the following error:

Cannot load "serverless.ts": Initialization error: TSError: ⨯ Unable to compile TypeScript:
  serverless.ts:50:1 - error TS1203: Export assignment cannot be used when targeting ECMAScript modules. Consider using 'export default' or another module format instead.

Obviously I have tried export default, module.exports, with no luck. I believe one of the solutions is to have separate tsconfig.json files for serverless and vue... however I was hoping there was a simpler solution for serverless.ts to be compatible with ES modules - my project is pretty small, I am the only developer, I'm trying to avoid having multiple configurations / repos when not necessary.

I have reproduced the issue in a repo for your convenience: https://github.com/cohlar/sls-ts-example (here the issue is with the import, but if I do not import the function here, then the issue becomes an export issue... basically same source of issue).

Many thanks for your help, Larry

fredericbarthelet commented 3 years ago

Hello @cohlar and thanks for submitting your issue. I'll take a look at current tsconfig module parameter set to CommonJS instead of esnext, thanks for pointing this out.

As far as using the same tsconfig file for both your frontend code base and your backend, I would not want to do that. There are a few additional parameters other than module to take into consideration :

It may be way easier to host both frontend and backend code base on the same repository, but in different folder, each with their own tsconfig configuration. WDYT :) ?

cohlar commented 3 years ago

Hi, you are absolutely right. I'm pretty new to TypeScript and to the concept of monorepos, I try to keep my codebase as simple as I can, but here you're right it doesn't make sense - thanks for pointing that out!

fredericbarthelet commented 3 years ago

Glad I could help :) I'll close this in the meantime, do not hesitate if you need additional information!