【问题标题】:failed to load wasm application无法加载 wasm 应用程序
【发布时间】:2020-10-11 19:59:29
【问题描述】:

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

我的主要代码在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 程序集文件的正确方法是什么?

【问题讨论】:

标签: javascript apache fetch mime-types webassembly


【解决方案1】:

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

事实上,一切都在this page

当您编译项目而不希望使用捆绑程序运行它时,您必须使用 --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)

您将 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 ...)。如果你使用 npm 处理一个大项目,你可能需要一个。否则,“--target web”会告诉 wasm-bindgen 实例化 wasm 模块the right way(查看pkg/test_wasm.js

【讨论】:

  • '服务器以非 Javascript MIME 类型的应用程序/WASM 响应'。这个错误对我来说毫无意义。有人可以解释一下这是什么意思。我正在尝试使用 WASM 并收到一条消息,说服务器使用 WASM 响应 - 该错误与 Prolog 的“否”一样有用。现在是 2021 年——我们还没有进步一点点吗?
  • 你是救生员!
  • @PaulMcCarthy 我的编辑回答你的问题了吗?
  • 如果你这样做会发生什么:const math = awaitWebAssembly.instantiateStreaming(fetch('math.wasm')) .then(res =&gt; res.instance.exports)
猜你喜欢
  • 2015-04-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-17
  • 2017-04-15
  • 2016-10-28
  • 2016-07-20
  • 2013-02-09
  • 1970-01-01
相关资源
最近更新 更多