Packaging, Publishing & CI
local graph
Chapter 13 — Packaging, Publishing & CI
Section titled “Chapter 13 — Packaging, Publishing & CI”Chapter 13 – Packaging, Publishing & CI
Section titled “Chapter 13 – Packaging, Publishing & CI”Shipping your Rust–Wasm package smoothly to npm and automating releases ensures that teammates and customers get updates reliably.
13.1 npm Module Conventions
Section titled “13.1 npm Module Conventions”When you publish a Rust–Wasm package to npm, you’re inviting JavaScript and TypeScript developers to consume your module just like any other library. Getting your package.json right is key to smooth installs, proper tree-shaking, and great DX. In this guide, we’ll break down each field, show you a real example, and share insider tips from production experiences.
flowchart TB A[Run wasm-pack build] —> B[pkg/ folder with .js, .wasm, .d.ts] B —> C[Craft pkg/package.json] C —> D[npm publish pkg] D —> E[Consumer does npm install + import]
1. Essential Fields in pkg/package.json
Section titled “1. Essential Fields in pkg/package.json”{ "name": "fast-math-wasm", // 1 "version": "0.2.1", // 2 "description": "Blazing-fast math ops in Rust–Wasm", "main": "fast_math_wasm.js", // 3 "module": "fast_math_wasm.js", // 4 "types": "fast_math_wasm.d.ts", // 5 "files": [ // 6 "fast_math_wasm.js", "fast_math_wasm_bg.wasm", "fast_math_wasm.d.ts" ], "sideEffects": false, // 7}“keywords”: [“wasm”, “rust”, “math”], “repository”: { “type”: “git”, “url”: “https://github.com/you/fast-math-wasm.git” }, “homepage”: “https://github.com/you/fast-math-wasm#readme”, “license”: “MIT”, “author”: “Your Name [email protected]” }
-
name
- Must be unique on npm.
- Follow npm naming conventions.
-
version
- Follows SemVer: MAJOR.MINOR.PATCH.
- Keep in sync with your Cargo.toml to avoid confusion.
-
main
- Entry point for CommonJS consumers (e.g., Node.js).
- Points to the generated JS glue (*_wasm.js).
-
module
- Entry for ESM bundlers (Vite, Rollup).
- Allows tree-shaking—unused exports are dropped.
-
types
- Points to the TypeScript declarations (.d.ts) emitted by wasm-pack.
- Ensures IDEs and TS compilers get autocomplete and type safety.
-
files
- Limits what goes into the published tarball.
- Excludes examples, tests, and any extra build artifacts.
-
sideEffects: false
- Signals bundlers that importing your module has no global side-effects.
- Enables safe tree-shaking of unused exports, reducing final bundle size.
- Handling Multiple Targets
If you support both browser and Node.js targets, you might build twice:
pkg/ ├── bundler/ // for ESM/browser │ ├── fast_math_wasm.js │ └── fast_math_wasm_bg.wasm └── nodejs/ // for Node.js ├── fast_math_wasm.js └── fast_math_wasm_bg.wasm
You can then publish both under different sub-directories and document it in your README:
Browser (ESM)
import init, { add } from 'fast-math-wasm/bundler';await init();console.log(add(2, 2)); // 4Node.js
import init, { add } from 'fast-math-wasm/nodejs';await init();console.log(add(2, 2));3. Real-World Case Study
Section titled “3. Real-World Case Study”Scenario: My team shipped a Wasm-powered image filter library. Omitting sideEffects: false meant Webpack couldn’t safely drop unused filters—our bundle fattened by nearly 25 KB. Adding sideEffects: false immediately enabled dead-export removal, cutting our shipped code by 40%.
4. Insider Tips
Section titled “4. Insider Tips”- Keep names short but descriptive. Avoid deep paths.
- Sync versions via a script or cargo-release to bump both Cargo.toml and package.json together.
- Lock file references: consumers won’t see your pkg folder structure—document entry points clearly in your README.
<!-- page: 154 -->
- Test installs with `npm pack && tar -xz` locally to ensure no stray files slip into your package.- Provide a browser-friendly CDN path (e.g., unpkg link) in README for quick demos.
---
# 13.2: Versioning and Release Workflows
Consistent versioning and automated release processes keep your Rust→Wasm package reliable and predictable for consumers.
---
flowchart LRA[Developer Merge to main] --> B[Create Git Tag vX.Y.Z]B --> C[CI Pipeline Triggers]C --> D[Build & Test Wasm]D --> E[Generate Changelog]E --> F[Publish to crates.io & npm]F --> G[Create GitHub Release with assets]
---
## 1. Semantic Versioning Principles
Follow SemVer for clarity:
- **PATCH** (0.2.3 → 0.2.4): Bug fixes, documentation updates—no new features.- **MINOR** (0.2.4 → 0.3.0): Backward-compatible feature additions.- **MAJOR** (0.3.0 → 1.0.0): Breaking API changes, dropped functionality, or altered behaviors.
### Expert Commentary:
Rigorous SemVer discipline lets downstream bundlers and frameworks predictably bump or lock dependencies, avoiding silent breakage.
---
## 2. Synchronizing Rust and npm Versions
<!-- page: 155 -->
Your Rust crate’s `Cargo.toml` and your npm `package.json` both carry versions. Keep them in sync:
## A. Using cargo-release
`cargo-release` automates version bumps across Cargo and npm:
### 1. Install
bashcargo install cargo-release2. Configure in Cargo.toml:
Section titled “2. Configure in Cargo.toml:”[package.metadata.release]push = truepush-remote = "origin"npm = truenpm-tag = "latest"npm-publish = true3. Run
Section titled “3. Run”# Bump patch versioncargo release patch# For a minor feature:cargo release minor# For a breaking change:cargo release majorWhat happens:
Section titled “What happens:”- Updates
Cargo.tomlversion - Updates
pkg/package.jsonversion - Commits changes, tags vX.Y.Z, pushes to Git
- Publishes to crates.io and npm
Case Study:
Section titled “Case Study:”A library maintainer I worked with reduced release errors by 90% after adopting cargo-release—no more mismatched versions or forgotten publishes.
3. Automating Changelog Generation
Section titled “3. Automating Changelog Generation”A clear changelog helps users understand what changed in each version. Conventional Commits + tooling makes this effortless.
A. Conventional Commits
Section titled “A. Conventional Commits”Adopt a commit message style like:
feat(parser): support new CSV header format fix(render): correct off-by-one in drawing routine docs: update README with usage example
## B. Generating the Changelog
1. **Install the CLI:**
```bash npm install --save-dev conventional-changelog-cli-
Add a script to package.json:
{"scripts": {"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s"}} -
Run before releasing:
Terminal window npm run changeloggit add CHANGELOG.mdgit commit -m "chore: update changelog for vX.Y.Z"
Personal Insight:
Section titled “Personal Insight:”Generating changelogs from commit history saved me from endless “what changed in 2.1.0?” questions—your future self and users will thank you.
4. Putting It All Together: A Release Flow
Section titled “4. Putting It All Together: A Release Flow”- Feature / Bug Branch
- Work in a feature branch, use Conventional Commits.
- Merge into main via PR.
-
Tag and Release
-
On main:
Section titled “On main:” -
git tag v1.2.0
-
git push —follow-tags
-
CI Pipeline sees the tag, runs:
- cargo test & wasm-pack test
- wasm-pack build —release
- npm run changelog
- cargo release from-tag (or npm publish pkg)
- Creates a GitHub Release with the changelog entry as the release notes.
on: create: tags: - ‘v*..’
jobs: release: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions-rs/toolchain@v1 with: toolchain: stable - run: cargo test —release - run: wasm-pack build —release —target bundler —out-dir pkg - run: npm ci && npm run changelog && git add CHANGELOG.md && git commit -m “chore: update changelog” - uses: ncipollo/release-action@v1 with: tag: {{ secrets.NPM_TOKEN }}
Expert Tip: Automate as much as possible—manual version bumps and publishes invite errors. Review your CI logs carefully on first runs to catch path or authentication issues.
Summary
Section titled “Summary”- Adhere to SemVer: PATCH, MINOR, MAJOR.
- Use
cargo-releaseto sync versions across Rust and npm, tag, and publish in one command. - Generate changelogs from commit history via Conventional Commits and
conventional-changelog. - Wire up CI to test, build, update docs, publish artifacts, and create releases automatically.
13.3 GitHub Actions Example Pipeline
Section titled “13.3 GitHub Actions Example Pipeline”A solid CI pipeline does more than run tests—it builds, verifies, and publishes your Rust→Wasm package automatically. Below is an in-depth look at a GitHub Actions workflow tailored for a wasm-pack-powered project, complete with testing in real browsers, linting, size checks, and gated publishing on semver tags.
flowchart TB subgraph Trigger Events A[push to main] B[create tag vX.Y.Z] end A —> C[build-and-test job] B —> C C —> D[Lint JS & TS] C —> E[Rust wasm-pack tests (Chrome + Node)] C —> F[Build Wasm (release)] F —> G[Size & smoke-checks] G —> H{Is tag?} H —>|yes| I[publish job] H —>|no| J[stop] I —> K[Publish to npm] I —> L[Create GitHub Release]
---
## 1. Workflow Triggers
<!-- page: 159 -->
on: push: branches: [ main ] # Run tests on every merge create: tags: - 'v*.*.*' # On semver tag creation,trigger release
- push to main ensures your code is continuously validated.- create tag (e.g. v1.2.3) gates the publish job—only tagged commits produce npm releases.
---
## 2. Job: build-and-test
jobs: build-and-test: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v3
- name: Setup Rust toolchain uses: actions-rs/toolchain@v1 with: toolchain: stable components: wasm32-unknown-unknown
- name: Install wasm-pack run: cargo install wasm-pack --version 0.10.3
- name: Run Rust unit & wasm-pack tests run: wasm-pack test --headless --chrome -- --no-run=false
- name: Build Wasm (release) run: wasm-pack build --release --target bundler --out-dir pkg
- name: Install Node.js uses: actions/setup-node@v3 with: node-version: '16'
- name: Install JS deps & lint run: | npm ci
<!-- page: 160 -->
npm run lint
- name: Smoke-check bundle size run: | ls -lh pkg/*.wasm # Optionally fail if >200KB
## Commentary
1. **Rust tests in real Wasm contexts** - `--headless --chrome` catches browser-specific interop bugs.
2. **Release build** - Uses your `Cargo.toml` LTO and size configs.
3. **JS linting** - Guards against invalid import paths or TS mismatches.
4. **Smoke-check** - A simple size check prevents runaway payloads.
---
## 3. Job: publish
```yamlpublish: needs: build-and-test if: startsWith(github.ref, 'refs/tags/v') runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v3
- name: Setup Node.js & auth uses: actions/setup-node@v3 with: node-version: '16' registry-url: 'https://registry.npmjs.org' - run: echo "//registry.npmjs.org/:_authToken=${{ secrets.NPM_TOKEN }}" > ~/.npmrc
- name: Publish to npm run: npm publish pkg --access public
- name: Create GitHub Release uses: ncipollo/release-action@v1 with: tag: ${{ github.ref_name }}name: Release (sed -n ‘1,200p’ CHANGELOG.md) # first section of changelog
Commentary
Section titled “Commentary”- Conditional on tag: the if guard ensures only semantic-version tags trigger publishing.
- secrets.NPM_TOKEN: safely authenticates without exposing credentials.
- GitHub Release: attaches detailed notes from your CHANGELOG.md automatically.
4. Personal Insights & Best Practices
Section titled “4. Personal Insights & Best Practices”- Split “build-and-test” vs. “publish” into separate jobs for clarity and faster feedback on test failures.
- Pin tool versions (e.g., [email protected]) to prevent CI drift when new releases introduce breaking changes.
- Use smoke tests on .wasm size rather than a hard threshold—combine with alerts to track growth over time.
- Changelog excerpts in release notes provide immediate context to users browsing your GitHub Releases page.
By following this pipeline, you’ll automate everything from rigorous Wasm testing to safe, gated npm publishes—letting you focus on code, not release mechanics.