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