Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fails to import as default in serverless env. #162

Open
amir-ziaei opened this issue Nov 14, 2022 · 2 comments
Open

Fails to import as default in serverless env. #162

amir-ziaei opened this issue Nov 14, 2022 · 2 comments

Comments

@amir-ziaei
Copy link

I have a ts serverless repo with the following tsconfig.json:

{
  "compilerOptions": {
    "strict": true,
    "preserveConstEnums": true,
    "strictNullChecks": true,
    "sourceMap": true,
    "allowJs": true,
    "target": "es5",
    "outDir": ".build",
    "moduleResolution": "node",
    "lib": ["es2015"],
    "rootDir": ".",
    "baseUrl": ".",
    "paths": {
      "test-utils/*": ["tests/utils/*"],
      "~/*": ["src/*"]
    },
    "resolveJsonModule": true
  }
}

When I import tiny-invariant with its default import (import invariant from 'tiny-invariant') , my serverless crashes:

TypeError: (0 , tiny_invariant_1.default) is not a function

But if I import it using named import (import * as invariant from 'tiny-invariant'), it works fine except now my vscode starts complaining:

This expression is not callable.
  Type 'typeof import(".../node_modules/tiny-invariant/dist/tiny-invariant")' has no call signatures.ts(2349)

Is there something wrong with my configuration?

@ngregrichardson
Copy link

I'm having the same problem with a similar setup, is there any update on this?

@marcesengel
Copy link

marcesengel commented Dec 26, 2024

This is because there's a "discrepancy" between the typescript declaration file (dist/tiny-invariant.d.ts) and the CJS distribution (dist/tiny-invariant.cjs.js) - the first specifying a default export (-> which is why your IDE thinks you can only use a default import) and the latter specifying a CJS root export (module.exports = invariant).

When you now convert your code to CJS before running it (due to target being set to es5), tsc will import invariant using const invariant = require('tiny-invariant').default - which won't work, due to it being exported directly (not as default) in tiny-invariant.cjs.js.

Unless there's some specific reason for you not to do it, this is easily fixed by enabling the esModuleInterop ts compiler option.

It seems this was different in the past, leading to issue #60 😂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants