Thursday, 8 December 2022

Javascript - Function returning different result when imported from a package

I have a function that is a part of my utils package that I import in my other modules:

export function urlQueryParamParser(params: URLSearchParams) {
  const output:any = {};
  const searchParams = new URLSearchParams(params);

  new Set([...searchParams.keys()])
    .forEach(key => {
      output[key] = searchParams.getAll(key).length > 1 ?
        searchParams.getAll(key) :
        searchParams.get(key)
    });

  return output;
}

I export it like this in my index file along with other modules:

export * from './utils/urlQueryParamParser'

When I import it to my module:

import { urlQueryParamParser } from '@mypackages/utils'

and use it urlQueryParamParser(params) I get:

{
    "[object Iterator]": null
}

Where, if I just copy the function and use it as a part of the file where I am actually calling it, I get the right return result, something like this:

{
    "filter": "all",
    "query": "",
    "range": "today",
    "from": "2022-11-22",
    "to": "2022-12-22",
    "claims": [
        "damaged",
        "missing-article"
    ]
}

Why is the result different when I import this function as part of the other package from when I use it as a function in the file where I am calling it? The module where I am importing the function has following typescript version:

"typescript": "^4.7.2",

And the tsconfig.json of that module looks like this:

{
  "compilerOptions": {
    "baseUrl": "./src",
    "target": "ESNext",
    "allowJs": false,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "esModuleInterop": true,
    "module": "ESNext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "importHelpers": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "skipLibCheck": true
  },
  "include": ["src/**/*.ts", "src/**/*.tsx"],
  "files": ["custom.d.ts"]
}

The typescript version of the package module is:

"typescript": "^4.7.4"

And the tsconfig.json looks like this:

{
  "extends": "../../tsconfig.base.json",
  "compilerOptions": {
    "outDir": "./dist/", // path to output directory
    "baseUrl": "./src",
    "target": "esnext",
    "lib": ["dom", "dom.iterable", "esnext"],
    "module": "ESNext",
    "allowJs": false,
    "allowSyntheticDefaultImports": true,
    "forceConsistentCasingInFileNames": true,
    "isolatedModules": true,
    "importHelpers": true,
    "jsx": "react",
    "noEmit": false,
    "composite": true,
    "incremental": true,
    "declarationMap": true,
    "plugins": [{ "name": "typescript-plugin-css-modules" }]
  },
  "exclude": ["**/node_modules", "**/.*/", "dist", "build"],
  "include": ["src/**/*.ts", "src/**/*.tsx"]
}


from Javascript - Function returning different result when imported from a package

No comments:

Post a Comment