1

I'm writing a wasm library that I want to be available in both the browser and Node. Does this mean I need to run both wasm-pack publish -t bundler and wasm-pack publish -t node? Is there a way to publish both builds under the same package instead of publishing both mylib-node and mylib-browser?

This should be a fairly simple task (this library doesn't rely on any browser-specific stuff) but I've been unable to find a recommended example workflow.

KevinH
  • 586
  • 1
  • 8
  • 12

1 Answers1

2

After investigating a bit, as this seems a natural feature, I found that this issue is discussed and expected on the wasm-pack github, and there seems to be work done towards a --target all that would do exactly what you say, but we are not there now, apparently.

There were some suggestions that seemed to work, especially this script:

#!/usr/bin/env bash

set -e

# Check if jq is installed
if ! [ -x "$(command -v jq)" ]; then
    echo "jq is not installed" >& 2
    exit 1
fi

# Clean previous packages
if [ -d "pkg" ]; then
    rm -rf pkg
fi

if [ -d "pkg-node" ]; then
    rm -rf pkg-node
fi

# Build for both targets
wasm-pack build -t nodejs -d pkg-node
wasm-pack build -t browser -d pkg

# Get the package name
PKG_NAME=$(jq -r .name pkg/package.json | sed 's/\-/_/g')

# Merge nodejs & browser packages
cp "pkg-node/${PKG_NAME}.js" "pkg/${PKG_NAME}_main.js"
sed "s/require[\(]'\.\/${PKG_NAME}/require\('\.\/${PKG_NAME}_main/" "pkg-node/${PKG_NAME}_bg.js" > "pkg/${PKG_NAME}_bg.js"
jq ".files += [\"${PKG_NAME}_bg.js\"]" pkg/package.json \
    | jq ".main = \"${PKG_NAME}_main.js\"" > pkg/temp.json
mv pkg/temp.json pkg/package.json
rm -rf pkg-node
TachyonicBytes
  • 700
  • 1
  • 8
  • And then does one just publish this with `npm publish`? – KevinH Feb 26 '23 at 19:53
  • Yes, the combination should produce a publishable package, so `npm publish` should suffice. I didn't have time to test the script myself for now, though. – TachyonicBytes Feb 26 '23 at 22:29
  • Note, the `jq` command isn't standard (at least on macOS) – Andrew Schoen Mar 01 '23 at 18:07
  • tried @TachyonicBytes's code, and I am getting two issues with this command as-is. First, since my package uses a namespace, it fails. I adjusted the merge section to replace all instances of `${PKG_NAME}` with `${PKG_NAME##*/}`, which seems to fix that specific issue. However, I still get `sed: pkg-node/mylib_bg.js: No such file or directory` – Andrew Schoen Mar 02 '23 at 21:12