如何通过 webpacker 添加 jstree 到 Rails

How to add jstree via webpacker to Rails

我有一个 Rails 6 应用程序,我在其中通过 yarn 添加了 jstree 库。我有 application.js 文件,其中 require 语句。我想做以下事情 $('#tree').jstree(); 但这会导致 function jstree undefined 异常。我应该如何要求它?

创建一个新的 Rails 应用程序:

rails new myapp
cd myapp

安装 jstree 和 jQuery(它取决于):

yarn add jstree jquery

创建一个新的控制器并查看:

rails g controller welcome index

启动开发服务器和 Rails 服务器:

./bin/webpack-dev-server
rails s

packs/application.js中:

require('../../../node_modules/jstree/dist/themes/default/style.min.css');
global.$ = require('jquery');
require('jstree');

$(() => {
  $('#jstree').jstree();
});

添加一些 HTML 到 welcome#index:

<div id="jstree">
  <ul>
    <li>Root node 1
      <ul>
        <li id="child_node_1">Child node 1</li>
        <li>Child node 2</li>
      </ul>
    </li>
    <li>Root node 2</li>
  </ul>
</div>

访问 http://localhost:3000/welcome/index 以查看 jstree 的运行情况。

HTH