๐Ÿ•ธ๏ธ Using rust modules in JavaScript/Web Development (Part 2 / 3) [Webpack]

  1. Do a build of rust modules to generate wasm output.
  2. Move the generated web.wasm file to the assets directory.

*Prerequisite:

Setup the rust project from Part 1 of this post. Follow the Setting up the rust project and Building wasm from rust part of the post.

Using rust modules on front-end using Webpack

Setting up a webpack based frontend project

  1. mkdir webpackasm && cd webpackasm โ€” creating the project directory
  2. git init && yarn init or git init && npm init โ€” initialising git and npm/yarn
  3. yarn add --dev webpack webpack-cli webpack-dev-server โ€” installing dependencies.
webpackasm
โ”œโ”€โ”€ index.html
โ”œโ”€โ”€ package.json
โ”œโ”€โ”€ src
โ”‚ โ””โ”€โ”€ index.js
โ”œโ”€โ”€ webpack.config.js
โ””โ”€โ”€ yarn.lock
<html>
<head>
<title>Webpack WASM</title>
</head>
<body>
Hello
<script type="text/javascript" src="bundle.js"></script>
</body>
</html>
const path = require('path');module.exports = {
entry: './src/index.js',
mode: process.env.NODE_ENV || 'development',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
{
"name": "webpackasm",
"version": "1.0.0",
"main": "index.js",
"author": "Atul R <atulanand94@gmail.com>",
"license": "MIT",
"scripts": {
"start": "webpack-dev-server --open",
"build": "webpack -p && cp index.html dist/index.html",
"clean": "rm -rf ./dist/*"
},
"devDependencies": {
"webpack": "^4.4.1",
"webpack-cli": "^2.0.13",
"webpack-dev-server": "^3.1.1"
}
}
console.log('I am alive!!!');
Basic webpack setup with live reload
  1. yarn add --dev wasm-loader rust-native-wasm-loader โ€” add the necessary loaders
  2. Modify the webpack.config.js to
const path = require('path');module.exports = {
entry: './src/index.js',
mode: process.env.NODE_ENV || 'development',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [{
test: /\.rs$/,
use: [{
loader: 'wasm-loader'
},
{
loader: 'rust-native-wasm-loader',
options: {
release: true
}
}]
}]
}
};
import loadWasm from 'path/to/the/lib.rs';console.log('I am alive!!!');loadWasm().then(result => {
const {add, subtract, multiply} = result.instance.exports;
console.log('4 + 2 = ', add(4, 2));
console.log('4 - 2 = ', subtract(4, 2));
console.log('4 * 2 = ', multiply(4, 2));
});
import loadWasm from 'path/to/the/lib.rs';
Loading rust modules using webpack

Source Code:

https://github.com/master-atul/rust-module-in-javascript-blog-series

References:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store