Skip to content

Commit

Permalink
Merge pull request #36 from heidemn/fix-import-for-importmap
Browse files Browse the repository at this point in the history
Add .js file extension to import, to make importmap work out of the box
  • Loading branch information
pimterry committed Jun 3, 2024
2 parents 0842adc + 3a916c4 commit 63ffc72
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
36 changes: 35 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,45 @@ console.log(textDecoder.decode(decompressedData)); // Prints 'some input'

You can also load it from a CDN like so:
```javascript
let brotli = await import("https://unpkg.com/brotli-wasm@1.3.1/index.web.js?module").then(m => m.default);
const brotli = await import("https://unpkg.com/brotli-wasm@3.0.0/index.web.js?module").then(m => m.default);
```

The package itself has no runtime dependencies, although if you prefer using `Buffer` over using `TextEncoder/TextDecoder` you may want a [browser Buffer polyfill](https://www.npmjs.com/package/browserify-zlib).

##### Using an importmap

If you've installed `brotli-wasm` as an NPM package, you can load it from your `node_modules` subfolder:

```html
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<script type="importmap">
{
"imports": {
"brotli-wasm": "/node_modules/brotli-wasm/index.web.js"
}
}
</script>
<script type="module" src="/main.js"></script>
</body>
</html>
```

```javascript
// main.js
import brotliPromise from 'brotli-wasm';
const brotli = await brotliPromise;

const input = 'some input';
const uncompressedData = new TextEncoder().encode(input);
const compressedData = brotli.compress(uncompressedData);
const decompressedData = brotli.decompress(compressedData);
console.log(new TextDecoder().decode(decompressedData)); // Prints 'some input'
```

#### In browser with streams:

```javascript
Expand Down
5 changes: 4 additions & 1 deletion index.web.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
// In pure ESM web bundles, you must call init() and wait for the promised result before you can
// call any module methods. To make that as easy as possible, this module directly exposes the
// init() promise result, and returns the methods at the end of the promise.
import init, * as brotliWasm from "./pkg.web/brotli_wasm";
// https://github.com/WICG/import-maps?tab=readme-ov-file#extension-less-imports
// For usage with an importmap, it's convenient to add the ".js" extension here, because browsers
// don't try to guess the file extension.
import init, * as brotliWasm from "./pkg.web/brotli_wasm.js";
export default init().then(() => brotliWasm);

0 comments on commit 63ffc72

Please sign in to comment.