无法加载 wasm 应用程序

ram*_*mbi 3 javascript apache fetch mime-types webassembly

我正在尝试托管一个网站,并且我使用了一个 .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.

细节

有多个文件,但这是一个想法:

我的 index.html 加载模块 bootstrap.js

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

我的主要代码在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';
Run Code Online (Sandbox Code Playgroud)

问题出在哪儿?

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

ram*_*mbi 6

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

事实上,一切都在这个页面上

当您编译项目而不希望使用打包器运行它时,您必须使用 --target 标志运行 wasm-pack build。

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

这将创建一个 .js 文件(pkg/test_wasm.js在我的示例中),其中包含加载 wasm 应用程序所需的一切。

然后这就是你如何使用由 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)
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

然后它起作用了!

编辑:

现在我对 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"

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

你用来从 ecmascipt 模块(例如有很多 nmp 包)到单个 js 文件的工具称为web-bundler(webpack、rollup、snowpack ...)。如果你使用 npm 处理一个大项目,你可能需要一个。否则,“--target web”会告诉 wasm-bindgen 以正确的方式实例化 wasm 模块(查看pkg/test_wasm.js