How to publish a library for both browser and Node using wasm-pack?

397 Views Asked by At

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.

1

There are 1 best solutions below

4
TachyonicBytes On

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