Standalone
If you are using a bundler, you may choose to skip this section.
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 WebAssembly"
    },
    "devDependencies": {
+       "cpp.js": "^1.0.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.
export default {
    paths: {
        config: 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.html and add the following content.
<!DOCTYPE html>
<html>
   <head>
      <meta charset = "utf-8">
      <title>Cpp.js Vanilla sample</title>
      <script src="./dist/myapp.browser.js"></script>
      <script>
        initCppJs({ path: './dist' }).then(({ MySampleClass }) => {
            document.querySelector('#cppMessage').innerHTML = MySampleClass.sample();
        });
      </script>
   </head>
   <body>
    <p>Response from c++ : <span id="cppMessage">compiling ...</span></p>
   </body>
</html>
To view the output, you can start a local server, such as using the serve command, within the project directory.
To add serve as a project dependency, follow these steps:
{
    "name": "myapp",
    "scripts": {
+      "start": "serve",
       "build": "cppjs build -p WebAssembly",
    },
    "devDependencies": {
+      "serve": "^14.2.3",
       "cpp.js": "^1.0.0"
    }
}
To start your project
- npm
- Yarn
- pnpm
- Bun
npm run start
yarn run start
pnpm run start
bun run start
Sample Source Code: You can access the sample source code from this link.