在Rails上使用外部JavaScript库时控制台出错。我正在使用Webpack

时间:2018-03-31 12:17:35

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

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

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

我使用的是webpack 3.11.0和Rails 5.1.5。

代码如下所示:

带有模板的新rails项目(包括gems: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

为帖子生成模型

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

为帖子生成控制器

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文件以实现卡片的滑动行为。 Haven已经能够走得更远,因为在开始时我应该使用Swing.Stack()(由库提供)的实例,但浏览器没有认识到这一点。

js文件看起来像这样:

javacript/deck.js

import Swing from "swing";

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

const stack = Swing.Stack();

我将deck.js模块包含在webpack包中的条目文件中:

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

非常感谢你的帮助!

1 个答案:

答案 0 :(得分: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