【问题标题】:Error on console when using an external JavaScript library on Rails. I'm Using Webpack在 Rails 上使用外部 JavaScript 库时控制台出错。我正在使用 Webpack
【发布时间】:2018-09-10 06:35:41
【问题描述】:

我使用 yarn 将一个名为 Swing 的 npm 库添加到我在 Rails 上的项目中。 https://github.com/gajus/swing

问题是,即使它使用新库成功编译,我在控制台上遇到错误并且似乎无法使用库的功能。

我正在使用 webpack 版本 3.11.0 和 Rails 5.1.5。

代码如下:

带有模板的新 Rails 项目(包括 gem:https://github.com/lewagon/rails-templates/blob/master/minimal.rb 和用于身份验证的 Devise gem):

rails new <app name> \
  --webpack \
  --database postgresql
  -m https://raw.githubusercontent.com/lewagon/rails-templates/master/devise.rb

为 Post 生成的模型

rails g model Post title:string photo:string content:text 

为 Post 生成的控制器

rails g controller posts 

controllers/posts_controller.rb 

def index
  //generates posts to display 
end 

为帖子生成索引视图。

/index.html.erb
//iterate over posts and build a card for each 

<div class="card"> populate card with post  </div>

添加了带有 Yarn 的 Swing npm 包(安装后依赖确实出现在 package.json 中)

yarn add swing

创建了用于实现卡片刷卡行为的 js 文件。无法更进一步,因为一开始我应该使用 Swing.Stack() 的实例(由库提供),但浏览器没有识别到​​这一点。

js 文件如下所示:

javacript/deck.js

import Swing from "swing";

const card = document.querySelectorAll(".card") 

const stack = Swing.Stack();

我在 webpack 捆绑的入口文件中包含了我的 deck.js 模块:

javascript/packs/application.js 

import "bootstrap";
import "../deck.js";

我在控制台中遇到的错误说:

deck.js:9 Uncaught TypeError: Cannot read property 'Stack' of undefined
    at Object.<anonymous> (deck.js:9)
    at Object.defineProperty.value (deck.js:51)
    at __webpack_require__ (bootstrap d955d73d3325972391a3:19)
    at Object.<anonymous> (application.js:1)
    at __webpack_require__ (bootstrap d955d73d3325972391a3:19)
    at bootstrap d955d73d3325972391a3:62
    at bootstrap d955d73d3325972391a3:62

非常感谢您的帮助!

【问题讨论】:

  • 是否可以从新的 Rails 应用程序开始添加说明以重现此错误?
  • @JackZelig 我刚刚添加了它们!太感谢了!如果您需要其他信息,请告诉我!
  • 谢谢伙计。如果您使用 CommonJS 语法,事情应该可以工作,即将 import Swing from "swing"; 更改为 const Swing = require("swing");。你能不能试着改变一下,让我知道它是否能解决你的问题。
  • @JackZelig 是的!有效!你是最棒的。导入不起作用有什么原因吗?非常感谢。
  • 好的,很高兴听到。让我添加一个正确的答案(如果你接受就好了)。

标签: ruby-on-rails npm webpack package.json yarnpkg


【解决方案1】:

你需要使用 CommonJS 语法,这意味着你的 import 语句从这里改变:

import Swing from "swing";

到这里:

const Swing = require("swing");

使用import 不起作用的原因在于该模块使其自身可供其他代码使用的方式。

如果您在 Rails 项目中打开 node_modules/swing/package.json,您会看到模块的入口点(main 属性)设置为“./dist/index.js”。

如果你随后打开dist/index.js,你会看到该模块使用 CommonJS 语法(这意味着 ES6 语法根本不可用):

exports.Card = _Card2.default;
exports.Direction = _Direction2.default;
exports.Stack = _Stack2.default;

参考:https://nodejs.org/docs/latest/api/modules.html#modules_exports

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-22
    • 2017-01-11
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多