【问题标题】:Rails 5: What is causing the `Can't find variable: module` error?Rails 5:导致“找不到变量:模块”错误的原因是什么?
【发布时间】:2019-07-10 19:29:10
【问题描述】:

我正在使用 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?是什么导致了错误?

【问题讨论】:

    标签: ruby-on-rails yarnpkg


    【解决方案1】:

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

    您可以通过 3 种不同的方式解决此问题:
    1) 使用 webpacker (https://github.com/rails/webpacker) 编译资产。
    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-29
      • 1970-01-01
      • 1970-01-01
      • 2015-04-08
      • 1970-01-01
      • 2020-12-13
      • 1970-01-01
      • 2012-07-05
      相关资源
      最近更新 更多