import qs is undefined, but works with require

Viewed 1480

I have a code that runs on NodeJS 14 on Google Cloud Functions, I am using typescript with tsc to compile my code.

import qs from 'qs'

console.log(`qs >>> ${qs})

The code above logs (in production)

qs >>> undefined

I think the problem is my tsconfig, could someone help to check if there is some something non usual on my configuration?

If I use require('qs') the code works.

My tsconfig.json:

{
  "compilerOptions": {
    "module": "commonjs",
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "outDir": "lib",
    "sourceMap": true,
    "strict": true,
    "target": "es2017",
    "allowSyntheticDefaultImports": true
  },
  "compileOnSave": true,
  "include": ["src", "tests"]
}
2 Answers

Try it with:

import * as qs from 'qs'

To specify external dependencies for Cloud Functions you have to follow these guidelines, which ask you to include the dependencies you need in your package.json file and once that is done, to load them, you have to use require().

This is the correct approach provided in the official GCP documentation for Cloud Functions using the NodeJS runtime. I believe you are following these steps from the results you're obtaining, but I fail to see why would you have to use import qs from 'qs' other than for using Typescript syntax specifically.

If the require() approach works for you, being this approach the one provided in the documentation, I suggest you to follow this procedure instead.

Related