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'));

4. const {sqrt} = require('mathjs');
5. 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');

6. const globals = require('rollup-plugin-node-globals');
7. const builtins = require('rollup-plugin-node-builtins');
8. const plugin_async = require('rollup-plugin-async');

10. const babelOptions = {
11. 'presets': ['@babel/preset-react']
12. };

14. module.exports = [
15. {
16. input: './npm_main.js',
17. output: {
18. inlineDynamicImports: true,
19. file: 'dist/npm_main.mjs',
20. format: 'esm',
21. },
22. external: ['process', 'wasi_net','std'],
23. plugins: [
24. plugin_async(),
25. nodeResolve(),
26. commonjs({ignoreDynamicRequires: false}),
27. babel(babelOptions),
28. globals(),
29. builtins(),
30. replace({
31. 'process.env.NODE_ENV': JSON.stringify('production'),
32. 'process.env.NODE_DEBUG': JSON.stringify(''),
33. }),
34. ],
35. },
36. ];

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.