Cloudflare Worker
You can use cpp.js to compile native code from your project into WebAssembly. To do this, add the build script and cpp.js as a dependency in the package.json file of your project.
{
"name": "myapp",
"scripts": {
+ "build": "cppjs build -p wasm",
"dev": "wrangler dev",
"deploy": "wrangler dev"
},
"devDependencies": {
+ "cpp.js": "^1.0.0-beta.1",
"wrangler": "^3.75.0"
}
}
To install the npm packages, use the following command:
- npm
- Yarn
- pnpm
- bun
npm install
yarn install
pnpm install
bun install
Cpp.js requires a configuration file to work. For a minimal setup, create a cppjs.config.mjs
file and add the following content.
import getDirName from 'cpp.js/src/utils/getDirName.js';
export default {
paths: {
project: getDirName(import.meta.url),
output: 'dist',
},
};
Move your C++ code to the src/native directory. For example;
#pragma once
#include <string>
class MySampleClass {
public:
static std::string sample() {
return "Hello World!";
}
};
Now, we can compile our C++ code into WebAssembly. Run the following command:
Before proceeding, ensure that you have met all the prerequisites for setting up a working development environment.
- npm
- Yarn
- pnpm
- bun
npm run build
yarn build
pnpm run build
bun run build
This command will generate myapp.wasm, myapp.browser.js, and myapp.node.js files inside the dist folder.
├── src
│ └── native
| └── MySampleClass.h
|
├── dist
│ └── myapp.wasm
| └── myapp.browser.js
| └── myapp.node.js
├── ...
You can now access your native code by importing dist/myapp.browser.js into your JavaScript file. For a minimal setup, create a index.js and add the following content.
import initCppJs from './dist/myapp.browser.js';
import wasmContent from './dist/myapp.wasm';
const { MySampleClass } = await initCppJs({ getWasmFunction: () => wasmContent });
export default {
async fetch(request, env, ctx) {
return new Response(MySampleClass.sample());
},
};
The project is now fully set up and ready to run. To view the output, run the following command:
- npm
- Yarn
- pnpm
- bun
npm run dev
yarn dev
pnpm run dev
bun run dev
To deploy the output, run the following command:
- npm
- Yarn
- pnpm
- bun
npm run deploy
yarn deploy
pnpm run deploy
bun run deploy
Sample Source Code: You can access the sample source code from this link.