build-wasm.sh 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #!/usr/bin/env bash
  2. set -euo pipefail
  3. function _print_usage {
  4. echo "Usage: $0 --target=web|nodejs [--no-container] -- [parameters for .devcontainer/env.sh]"
  5. echo
  6. echo "Use target 'web' to build for Threema Desktop and the examples."
  7. echo "Use target 'nodejs' to build for the bindings tests."
  8. echo "Use --no-container to not source a devcontainer environment."
  9. }
  10. while [[ "$#" -gt 0 ]]; do
  11. case "$1" in
  12. -h | --help)
  13. _print_usage
  14. exit 0
  15. ;;
  16. --target=web)
  17. _target='web'
  18. _build_dir='web'
  19. ;;
  20. --target=nodejs)
  21. _target='experimental-nodejs-module'
  22. _build_dir='nodejs'
  23. ;;
  24. --no-container)
  25. _no_container=1
  26. ;;
  27. --)
  28. shift;
  29. break
  30. ;;
  31. *)
  32. echo "Unknown parameter passed: $1"
  33. _print_usage
  34. exit 1
  35. ;;
  36. esac
  37. shift
  38. done
  39. if [[ -z ${_target+x} ]] || [[ -z ${_build_dir+x} ]] ; then
  40. _print_usage
  41. exit 1
  42. fi
  43. # Clean and load dev container
  44. cd "$(dirname "$0")/.."
  45. [[ -d "./build/wasm/${_build_dir}" ]] && rm -r "./build/wasm/${_build_dir}"
  46. if [[ -z ${_no_container+x} ]] ; then
  47. source ./.devcontainer/env.sh -q
  48. fi
  49. # Ensure consistent target dir, even if `build.target-dir` config option is set for Cargo
  50. export CARGO_TARGET_DIR=target
  51. # Build library as WASM
  52. cargo build \
  53. --locked \
  54. -F wasm \
  55. -p libthreema \
  56. --target wasm32-unknown-unknown \
  57. --release
  58. # Create WASM bindings for Rust code
  59. wasm-bindgen \
  60. --out-dir "./build/wasm/${_build_dir}" \
  61. --target "${_target}" \
  62. --encode-into always \
  63. --split-linked-modules \
  64. ./target/wasm32-unknown-unknown/release/libthreema.wasm
  65. # Optimise WASM
  66. # See: https://github.com/WebAssembly/binaryen/wiki/Optimizer-Cookbook
  67. wasm-opt \
  68. "./build/wasm/${_build_dir}/libthreema_bg.wasm" \
  69. -o "./build/wasm/${_build_dir}/libthreema_bg.wasm" \
  70. -O3 \
  71. --inline-functions-with-loops \
  72. --strip-toolchain-annotations
  73. # Unload dev container if it was started
  74. if [[ -z ${_no_container+x} ]] ; then
  75. deactivate --only-if-started
  76. fi