您如何使用 Rails 6 / webpacker 获取本地 Javascript 文件?
How do you require local Javascript files with Rails 6 / webpacker?
所以这似乎是一个简单的问题,但我找不到任何相关链接。
我正在使用 coffee-rails 并且有一个文件 app/javascript/packs/post_form.js.coffee
。我通过 javascript_pack_tag 'post_form'
.
将其包含在我的 HTML 页面中
问题是,如何从这里加载依赖的JS文件?我试着把 post_form.js.coffee
:
HelperFunctions = require("lib/helper_functions")
然后在app/javascript/lib/helper_functions.js.coffee
:
module.exports = {
UsefulMethod: -> console.log("I'm helpful!")
}
我得到
> 找不到模块 'lib/helper_functions'
我的config/webpack/environments.js
文件如下:
const { environment } = require('@rails/webpacker')
const coffee = require('./loaders/coffee')
const webpack = require('webpack')
environment.plugins.prepend('Provide', new webpack.ProvidePlugin({
$: 'jquery/src/jquery',
jQuery: 'jquery/src/jquery',
jquery: 'jquery',
'window.jQuery': 'jquery',
Popper: ['popper.js', 'default']
}))
environment.loaders.prepend('coffee', coffee)
module.exports = environment
你必须相对要求它。试试这个:
// app/javascript/packs/post_form.coffee
HelperFunctions = require("../lib/helper_functions");
所以这似乎是一个简单的问题,但我找不到任何相关链接。
我正在使用 coffee-rails 并且有一个文件 app/javascript/packs/post_form.js.coffee
。我通过 javascript_pack_tag 'post_form'
.
问题是,如何从这里加载依赖的JS文件?我试着把 post_form.js.coffee
:
HelperFunctions = require("lib/helper_functions")
然后在app/javascript/lib/helper_functions.js.coffee
:
module.exports = {
UsefulMethod: -> console.log("I'm helpful!")
}
我得到
> 找不到模块 'lib/helper_functions'
我的config/webpack/environments.js
文件如下:
const { environment } = require('@rails/webpacker')
const coffee = require('./loaders/coffee')
const webpack = require('webpack')
environment.plugins.prepend('Provide', new webpack.ProvidePlugin({
$: 'jquery/src/jquery',
jQuery: 'jquery/src/jquery',
jquery: 'jquery',
'window.jQuery': 'jquery',
Popper: ['popper.js', 'default']
}))
environment.loaders.prepend('coffee', coffee)
module.exports = environment
你必须相对要求它。试试这个:
// app/javascript/packs/post_form.coffee
HelperFunctions = require("../lib/helper_functions");