Rails 5: 是什么导致“无法找到变量:模块”错误?

Rails 5: What is causing the `Can't find variable: module` error?

我正在使用 Yarn 将 JS 模块添加到我的 Rails 应用程序。

我添加了 Google 的 markerclusterer.js。 yarn add marker-clusterer-plus

然后我将其导入 application.js.erb//= require marker-clusterer-plus/src/markerclusterer.js

有效,但我在控制台中看到错误:ReferenceError: Can't find variable: module

深入研究代码,我发现有问题的行是:

module.exports = MarkerClusterer

现在我力不从心了。我知道 module.exports 是一种公开代码以在其他文件中重用的方法。我理解它是标准的 JS。那么,如果它是标准 JS,是什么导致了错误消息?

我是否正确使用了 Yarn?是什么导致了错误?

看起来 marker-clusterer-plus/src/markerclusterer.js 不能在浏览器中使用,除非你用一些工具编译它。例如,您可以使用 webpack/webpacker 来编译 JavaScript.

的现代版本

您可以通过 3 种不同的方式解决此问题:
1)使用webpacker(https://github.com/rails/webpacker)编译assets
import 'marker-clusterer-plus/src/markerclusterer.js'; 在我的机器上没有出现任何错误。
2) 使用 CDN:
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-marker-clusterer/1.0.0/markerclusterer.js"></script> 此文件不包含 module.exports = MarkerClusterer,因此不会出现错误。
3) 下载 https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js(此文件不包含 module.exports = MarkerClusterer)。
将其放入 javascripts 文件夹。
//= require markerclusterer.js 放入 application.js