Skip to content

Commit

Permalink
Add doc about asset helper
Browse files Browse the repository at this point in the history
  • Loading branch information
myl7 committed Nov 20, 2023
1 parent a3d3b16 commit afd36ac
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
40 changes: 40 additions & 0 deletions doc/asset.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Asset helper

This package exports an entry `brotli-dec-wasm/asset` to help you bundle it with bundlers like webpack

## Usage

An example for webpack is available in [example/webpack-asset]

[example/webpack-asset]: example/webpack-asset

Briefly speaking, your code should look like:

```js
import brotliDecWasmPromise from 'brotli-dec-wasm/asset'

const brotliDecWasm = await brotliDecWasmPromise
brotliDecWasm.decompress(uint8Array)
```

Additionally you need to configure the bundler so that `import wasm from './pkg/index_bg.wasm'` can be handled by importing the WASM file as bytes, a URL string, or any other one that can be passed to `WebAssembly.instantiate`.
For webpack, you can use [Asset Modules] with `asset/resource` (imported as a URL string).

[Asset Modules]: https://webpack.js.org/guides/asset-modules/

If you are not satisfied with the import and want to use, e.g., `resourceQuery` condition, since the WASM binary file is exported, you can:

```js
import { init } from 'brotli-dec-wasm'
import wasm from 'brotli-dec-wasm/pkg/index_bg.wasm?url'

const brotliDecWasm = await init(wasm)
```

## Alternatives

wasm-pack ships a `bundler` target which emits code with `import * as wasm from './pkg/index_bg.wasm'`.
However, while looks similar, wasm-pack expects the import result to be a `WebAssembly.Module`, which then requires `syncWebAssembly: true` for webpack 5.
But webpack 5 already suggests users migrating to `asyncWebAssembly: true`, which requires `import('./pkg/index_bg.wasm')`.
Not to say some other bundlers require plugins to support WASM and have various import methods.
This asset helper is a bypass for WASM over the module resolution system in the web / web worker environment (URLs available) and should makes things a little easier.
3 changes: 3 additions & 0 deletions example/webpack-asset/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import brotliDecWasmPromise from 'brotli-dec-wasm/asset'
// import wasm from 'brotli-dec-wasm/pkg/index_bg.wasm'
// import { init } from 'brotli-dec-wasm'

async function main() {
const brotliDecWasm = await brotliDecWasmPromise
// const brotliDecWasm = await init(wasm)
window.brotliDecWasm = brotliDecWasm
}

Expand Down

0 comments on commit afd36ac

Please sign in to comment.