rs-wasm-loader
Version:
A webpack loader for Rust
56 lines (43 loc) • 1.9 kB
JavaScript
const path = require('path')
const toml = require('toml')
const fs = require('fs')
const childProcess = require('child_process')
module.exports = function (source) {
const callback = this.async()
const rootPath = this.rootContext
const target = 'wasm32-unknown-unknown'
fs.readFile(`${rootPath}/Cargo.toml`, 'utf-8', (e, file) => {
if (e) return callback(e)
const cargoToml = toml.parse(file)
const packageName = cargoToml.package.name.replace(/\-/g, "_")
const libPath = cargoToml.lib.path || 'src'
const outPath = path.join(rootPath, "target", target, "release", `${packageName}.wasm`)
const cmd = `cargo build --target=${target} --release`
childProcess.exec(cmd, { cwd: rootPath }, (e, stdout, stderr) => {
if (e) return callback(e)
fs.readFile(outPath, 'base64', (e, base64) => {
if (e) return callback(e)
const glueCode = `
function _atob(base64) {
if(typeof atob === 'function') {
return atob(base64)
}
else {
return Buffer.from(base64, 'base64').toString('binary')
}
}
function decode(encoded) {
let binaryString = _atob(encoded)
let bytes = new Uint8Array(binaryString.length)
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i)
}
return bytes.buffer
}
module.exports = WebAssembly.instantiate(decode("${base64}"), {})
`
callback(null, glueCode)
})
})
})
}