importmap 那套东西没有代码提示,用着实在是有点难受,换成前端构建工具之后又不知道怎么做到 lazyLoadControllersFrom 的效果。
你需要使用 shakapacker (webpacker 的后续),这样才能用 webpack 5 的 chuck 方式分包方式打包。
在需要的 html.erb 页面上引入需要的延迟加载组件。
<% content_for :head do %> <%= append_stylesheet_pack_tag 'selectize' %> <%= append_javascript_pack_tag 'selectize' %> <% end %>
app/javascript/packs/selectize.js
import $ from 'jquery' global.$ = $ global.jQuery = $ import '@selectize/selectize/dist/js/selectize'; require("lazy_controllers/selectizes");
app/javascript/lazy_controllers/selectizes.js:
import { Controller } from "@hotwired/stimulus" Stimulus.register("selectizes", class extends Controller { static targets = [ "select" ] connect() { $(this.selectTarget).selectize({ plugins: ["remove_button"] }); } disconnect() { const need_destroy = $(this.selectTarget)[0].selectize; if(need_destroy) { need_destroy.destroy(); } } });
具体模版