首页 文章

如何在js erb模板中使用rails webpack加载js

提问于
浏览
1

我在rails 5.0应用程序中使用webpacker gem,但我可以__97973_ m命中验证错误 . 我在这里违反了一些简单的前提,但找不到答案,也没有编译或控制台错误 . 我的application.html.erb中有 <%= javascript_pack_tag 'application' %>

这是设置:

应用程序/ JavaScript的/包/ application.js中:

import * as CustomerSession from 'customer_sessions';
console.log('Hello World from Webpacker');

应用程序/ JavaScript的/ customer_sessions / index.js:

export { univgwTabs } from './univgwTabs';

应用程序/ JavaScript的/ customer_sessions / univgwTabs:

export let univgwTabs = () => {
  console.log('hi');
};

js erb模板调用表单的验证错误:

$("#right_side_right_bottom_target").html("<%= j render partial: 'generic_object_new' %>");
CustomerSession.univgwTabs();
Global.resizeWindow();

1 回答

  • 3

    如果 console.log(CustomerSession) 在您导入它的位置没有问题,那么我找到的最简单的修复方法是将导入的变量指定为全局窗口属性之一 .

    // in packs/application.js (or wherever your pack is)
    // import
    import * as CustomerSession from 'customer_sessions';
    
    // assign
    window.CustomerSession = CustomerSession
    

    假设webpacker没有问题,您现在应该能够在控制台或 js.erb 文件中使用 console.log(CustomerSession) .

相关问题