我想从我的刺激控制器中的 javascript/helpers/functions.js
文件中导入和使用函数。
我尝试用以下方式固定它:
# importmap.rb
pin_all_from "app/javascript/helpers", under: "helpers"
将其添加到资产预编译中:
# asset.rb
Rails.application.config.assets.precompile += ['helpers/*']
我还尝试以不同的方式(不是一次全部)导入 application.js
中的文件:
// These are all the ways I tried to import the helpers folder in application.js
//= require_tree helpers
import "helpers"
import "./helpers"
在我的刺激控制器中,我像这样导入它
// javascript/controllers/select_controller.js
import {show, hideAll} from "helpers/functions";
据我了解,这应该可以工作,因为 importmap 将其映射到 helpers 命名空间,但我也尝试像这样导入它:
// javascript/controllers/select_controller.js
import { show, hideAll} from "../helpers/functions"
我尝试了上述各种变体,它在本地开发中运行良好,但每当我在生产环境中运行应用程序时,helpers
文件夹都不会被编译或出现 404 错误。
如何以正确的方式在 Stimulus 控制器中使用 JS 助手?
回答1
找到了解决我自己问题的方法:
# importmap.rb
pin_all_from "app/javascript/helpers", under: "helpers"
我需要在 application.js 中导入特定的帮助文件(function.js):
// application.js
import "helpers/functions"
在刺激控制器中:
// javascript/controllers/select_controller.js
import {show, hideAll} from "helpers/functions";