未能加载 wasm 应用程序

failed to load wasm application

我正在尝试托管一个网站,我使用 .wasm 文件和由 wasm-pack 工具创建的 .js 脚本。

我在本地用 npmnode.js 测试了项目,一切正常。

但后来我将它托管在树莓派 (apache2) 上,当我尝试访问它时,出现以下错误:

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.

详情

有多个文件,但思路如下:

my index.html 加载模块 bootstrap.js

// bootstrap.js content
import("./index.js").catch(e => console.error("Error importing `index.js`:", e));

我的主要代码在 index.js 中,它调用 test_wasm_bg.js

最后,test_wasm_bg.js 使用此行加载 wasm 文件:

// test_wasm_bg.js first line
import * as wasm from './test_wasm_bg.wasm';

问题出在哪里?

加载 Web 程序集文件的正确方法是什么?

我终于找到了在 wasm-bindgen 项目中加载 wasm 应用程序的正确方法!

事实上,一切都在 this page

当您编译项目而不想 运行 使用捆绑器时,您必须 运行 wasm-pack 使用 --target 标志构建。

wasm-pack build --release --target web.

这将创建一个 .js 文件(在我的示例中为 pkg/test_wasm.js),其中包含加载 wasm-application.

所需的所有内容

然后这就是您如何使用 wasm-bindgen (index.js) 创建的函数:

import init from './pkg/test_wasm.js';
import {ex_function, ex_Struct ...} from '../pkg/test_wasm.js';

function run {
    // use the function ex_function1 here

}

init().then(run)

您将 index.js 包含在 HTML 文件中

<script type="module" src="./index.js"></script>

然后就成功了!

编辑:

现在我对 javascript 生态系统有了更多的了解,我试着解释一下我的理解: 有很多方法可以在 js 中进行导入,这里是一个列表: https://dev.to/iggredible/what-the-heck-are-cjs-amd-umd-and-esm-ikm

除了 wasm-pack 的默认目标是节点样式 ecmascript module 之外,您不需要了解太多。此导入将在 node.js 中运行,但不能直接在浏览器中运行。所以在 node 中,你可以直接从 wasm 文件中导入一个函数,就像这样: import {ex_function} from "./test.wasm"

但是这些导入方式目前在浏览器中不起作用。也许会有可能in the future 但是现在,您的浏览器只知道 js 模块。所以如果你尝试直接在浏览器中导入一个 .wasm 文件,它会抛出 mime 类型错误,因为它不知道如何处理 webassembly 文件。

你用来从 ecmascipt 模块(例如有很多 nmp 包)到单个 js 文件的工具称为 web-bundler (webpack, rollup, snowpack ...). If you work on a big project with npm, you probably need one. Otherwise, the "--target web" will say to wasm-bindgen to instantiate the wasm module the right way(查看 pkg/test_wasm.js