ljharb / qs

A querystring parser with nesting support
BSD 3-Clause "New" or "Revised" License
8.47k stars 731 forks source link

Usage in the browser with importmap #507

Closed JH1ller closed 1 month ago

JH1ller commented 2 months ago

Hey there,

We're using qs in a ts library by importing it like this:

import { type IParseBaseOptions, parse, stringify } from 'qs';

We export our library as an esm bundle which is used in multiple contexts; installed as npm module (and then run in both server/node and client side) as well as directly within a script tag by utilizing import maps. This looks roughly like this:

<script type="importmap">
  {
    "imports": {
      "axios": "https://unpkg.com/axios@1.7.2/dist/esm/axios.js",
      "qs": "https://unpkg.com/qs@6.12.1/lib/index.js"
    }
  }
</script>
<script type="module">
  import { someFunction } from "./our-library/dist/index.js";
</script>

However, with this setup I get this error in the browser:

Uncaught SyntaxError: The requested module 'qs' does not provide an export named 'parse'

That's probably because qs only provides a CommonJS bundle and not an ESM bundle. From older issues it looks like you're quite apposed to ESM and will not add this option, but is there any other way I could use this library with an importmap?

My first approach was switching to https://www.npmjs.com/package/query-string which exports an esm bundle, but that library by design doesn't support nested objects.

ljharb commented 2 months ago

What transpiler and/or bundler are you using? import { parse } from 'qs' should work with anything that's configured properly. (for example, typescript's module system is utterly broken unless you've enabled synthetic imports and esModuleInterop)