1

So this seems like a simple question but I can't manage to find any links about it.

I am using coffee-rails and have a file app/javascript/packs/post_form.js.coffee. I am including it in my HTML page via javascript_pack_tag 'post_form'.

The question is, how do I load a dependent JS file from here? I tried putting inside post_form.js.coffee:

HelperFunctions = require("lib/helper_functions")

And then in app/javascript/lib/helper_functions.js.coffee:

module.exports = {
  UsefulMethod: -> console.log("I'm helpful!")
}

I'm getting

> Cannot find module 'lib/helper_functions'

My config/webpack/environments.js file is as follows:

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

1 Answer 1

3

You've to require it relatively. Try this:

// app/javascript/packs/post_form.coffee
HelperFunctions = require("../lib/helper_functions");
4
  • Unfortunately, it's not working. I tried putting a file test.js in the same directory as the script where I'm requireing it from. I couldn't get that to work with any permutation. With or without file extension, with or without ./. Nothing works. Jun 27, 2020 at 3:36
  • Strange, it's working for me. Don't use file.js.coffee, use file.coffee for coffee and file.js for JS file. Did you run rails webpacker:install:coffee to install coffeescript? You don't need to mention extensions in require whether that is .js or .coffee.
    – cdadityang
    Jun 27, 2020 at 3:58
  • Can you confirm that changing all your .js.coffee file to .coffee and restarting server still gives the same error?
    – cdadityang
    Jun 27, 2020 at 3:59
  • 1
    The reason for my confusion, was that I saw in a tutorial that the pack files can have extension .js.coffee and that is what I have - it works in that case. But it seems that when using require we reference plan .coffee extension. Jun 27, 2020 at 5:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.