Introduction

What is remux?

remux is a very handy RPC library/framework for writing local and remote functions in the same file, distinguished by the @remux tag.

Here’s a basic example, or you can open stackblitz to experience it:

// @remux server
function serverFunction() {
  console.log('Ouch!')
}

// @remux browser
{
  // put browser code here
  const btn = document.createElement('button')
  btn.innerText = 'Hit me'
  btn.addEventListener('click', () => serverFunction())
  document.body.appendChild(btn)
}

In the above example, the @remux browser part of the code creates a button and registers the click event as a closure that calls serverFunction, which prints the line Ouch! when the user clicks the button.

This example demonstrates two core features of remux, seamless remote calls and distinguishing code from multiple ends. Functions annotated with @remux are treated as remotes, while blocks of code are treated as running only on a specific end. As for @remux followed by server and browser, these two names are arbitrary, remux itself does not really care what the developer names, as long as it is passed to compiler.

Implementation Principle

remux provides a babel plugin to transpile source code.

It will wrap all functions tagged by @remux as calls to the _remuxInvoke function, and also add an import { _remuxInvoke } from '@remux/lib' to the start of the source, where @remux/lib can of course be changed to other libraries by parameter, it just the default is to use @remux/lib.

In addition, all code blocks, variable declarations and import statements that are tagged with @remux will be removed if they are not native. It is usually not necessary to mark variable declarations because tree-shaking at build time ensures that unused variables are removed, so if there is some sensitive information such as server keys, make sure that tree-shaking is turned on at build time, or else mark them to make sure that client-side code does not contain sensitive information.