我有一个使用emscripten进行编译的webassembly模块。现在,我正在尝试使用expressjs在网页中提供它。
我尝试遵循this gist来通过webpack包括webassembly,包括我发现的修改,因为该要旨稍大一些。
Webpack看起来像这样:
const path = require('path');
module.exports = {
optimization: {
mangleWasmImports: false
},
entry: './src/index.js',
output: {
path: path.resolve(__dirname, './dist/'),
filename: 'dynamic-graph.bundle.js'
},
target: "web",
module: {
rules: [
// Emscripten JS files define a global. With `exports-loader` we can
// load these files correctly (provided the global’s name is the same
// as the file name).
{
test: /fourd\.js$/,
loader: "exports-loader"
},
// wasm files should not be processed but just be emitted and we want
// to have their public URL.
{
test: /fourd\.wasm$/,
type: "javascript/auto",
loader: "file-loader",
options: {
publicPath: "dist/"
}
}
]
}
}
我在开发服务器上设置了https,因为我知道有时会导致问题。这是一个自签名证书,但是Chrome和Firefox让我解决了这个问题。
const express = require('express')
const fs = require('fs')
express.static.mime.types['wasm'] = 'application/wasm'
const https = require('https')
const app = express()
app.use('/', express.static(__dirname))
app.use((req, res, next) => {
res.header('X-Content-Type-Options', 'nosniff')
next()
})
https.createServer({
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.cert')
}, app).listen(8000, () => {
console.log('Listening...')
})
在以前的版本中,我能够使用Module.onRuntimeInitialized等待wasm模块被实例化。该代码仍然有效,我使用与以前相同的em ++标志(即-std=c++11 -s WASM=1 -s ALLOW_MEMORY_GROWTH=1 -s SAFE_HEAP=1 -O0 -g4 -s ASSERTIONS=1
我在浏览器中遇到的错误是:Failed to load module script: The server responded with a non-JavaScript MIME type of "application/wasm". Strict MIME type checking is enforced for module scripts per HTML spec.
,这使我陷入循环,因为我认为application / wasm正是MIME类型。