NodeJS and NPM module

With rollup.js, we can run CommonJS (CJS) and NodeJS (NPM) modules in WasmEdge too. The simple_common_js_demo/npm_main.js demo shows how it works. It utilizes the third-party md5 and mathjs modules.

  1. const md5 = require('md5');
  2. console.log('md5(message)=', md5('message'));
  3. const {sqrt} = require('mathjs');
  4. console.log('sqrt(-4)=', sqrt(-4).toString());

In order to run it, we must first use the rollup.js tool to build all dependencies into a single file. In the process, rollup.js converts CommonJS modules into WasmEdge-compatible ES6 modules. The build script is rollup.config.js.

  1. const {babel} = require('@rollup/plugin-babel');
  2. const nodeResolve = require('@rollup/plugin-node-resolve');
  3. const commonjs = require('@rollup/plugin-commonjs');
  4. const replace = require('@rollup/plugin-replace');
  5. const globals = require('rollup-plugin-node-globals');
  6. const builtins = require('rollup-plugin-node-builtins');
  7. const plugin_async = require('rollup-plugin-async');
  8. const babelOptions = {
  9. 'presets': ['@babel/preset-react']
  10. };
  11. module.exports = [
  12. {
  13. input: './npm_main.js',
  14. output: {
  15. inlineDynamicImports: true,
  16. file: 'dist/npm_main.mjs',
  17. format: 'esm',
  18. },
  19. external: ['process', 'wasi_net','std'],
  20. plugins: [
  21. plugin_async(),
  22. nodeResolve(),
  23. commonjs({ignoreDynamicRequires: false}),
  24. babel(babelOptions),
  25. globals(),
  26. builtins(),
  27. replace({
  28. 'process.env.NODE_ENV': JSON.stringify('production'),
  29. 'process.env.NODE_DEBUG': JSON.stringify(''),
  30. }),
  31. ],
  32. },
  33. ];

The package.json file specifies the rollup.js dependencies and the command to build the npm_main.js demo program into a single bundle.

  1. {
  2. "dependencies": {
  3. "mathjs": "^9.5.1",
  4. "md5": "^2.3.0"
  5. },
  6. "devDependencies": {
  7. "@babel/core": "^7.16.5",
  8. "@babel/preset-env": "^7.16.5",
  9. "@babel/preset-react": "^7.16.5",
  10. "@rollup/plugin-babel": "^5.3.0",
  11. "@rollup/plugin-commonjs": "^21.0.1",
  12. "@rollup/plugin-node-resolve": "^7.1.3",
  13. "@rollup/plugin-replace": "^3.0.0",
  14. "rollup": "^2.60.1",
  15. "rollup-plugin-babel": "^4.4.0",
  16. "rollup-plugin-node-builtins": "^2.1.2",
  17. "rollup-plugin-node-globals": "^1.4.0",
  18. "rollup-plugin-async": "^1.2.0"
  19. },
  20. "scripts": {
  21. "build": "rollup -c rollup.config.js"
  22. }
  23. }

Run the following NPM commands to build npm_main.js demo program into dist/npm_main.mjs.

  1. npm install
  2. npm run build

Run the result JS file in WasmEdge CLI as follows.

  1. $ wasmedge --dir .:. ../../target/wasm32-wasi/release/wasmedge_quickjs.wasm dist/npm_main.mjs
  2. md5(message)= 78e731027d8fd50ed642340b7c9a63b3
  3. sqrt(-4)= 2i

You can import and run any pure-JS NPM packages in WasmEdge this way.