16

From app/javascript/packs/application.js I'm trying to import "../foo" where the file is foo.js.erb. Webpacker and yarn are working great for other imports in application.js, for example import "../bar" when that file is bar.js but if I try with a .js.erb file I get this error from webpack-dev-server:

ERROR in ./app/javascript/packs/application.js
Module not found: Error: Can't resolve '../foo' in '/Users/blah/backlot/projects/test/app/javascript/packs'
 @ ./app/javascript/packs/application.js 3:0-27
 @ multi (webpack)-dev-server/client?http://localhost:8080 ./app/javascript/packs/application.js

I do have rails-erb-loader installed and if I look at the webpacker config, the erb loader is being evaluated and looks right to me although I didn't touch any of that except for running rails webpacker:install to generate that config.

Aurora0001
  • 13,139
  • 5
  • 50
  • 53
eagspoo
  • 2,095
  • 3
  • 22
  • 31

3 Answers3

26

If what you want to do is this:

import '../foo'

When the actual file is foo.js.erb, you need to update config/webpack/webpacker.yml to include

- .js.erb

In the list of extensions. Otherwise you need to fully specify the file name you are importing

import '../foo.js.erb'
RedBassett
  • 3,469
  • 3
  • 32
  • 56
eagspoo
  • 2,095
  • 3
  • 22
  • 31
  • 8
    It seems it is no longer `config/webpack/paths.yml` but `config/webpack/webpacker.yml` that must be updated. Confusingly, the list of extensions already contains `- .erb`, but the extension to add is `- .js.erb`. – KaptajnKold Aug 28 '17 at 11:43
  • 11
    Don't forget to install .erb support for webpacker first: https://github.com/rails/webpacker#erb – cseelus Apr 19 '18 at 17:03
  • 2
    Update for rails 6, the path is `config/webpacker.yml` – Mauricio Mora Jan 06 '20 at 01:36
  • By fixing the file extension to `.js.erb` in config/webpacker.yml does not require to load as `import '../foo.js.erb'`. – Fernando Kosh Mar 19 '20 at 00:56
14

To add Erb support in your JS templates, run bundle exec rails webpacker:install:erb on a Rails app already setup with Webpacker.

source (from cseelus' comment)

cdmo
  • 1,239
  • 2
  • 14
  • 31
8

For rails 6.x, run bundle exec rails webpacker:install:erb and add the following to the config/webpacker.yml

extensions:
  - .erb

See webpacker documentation for more info:

fydelio
  • 932
  • 1
  • 8
  • 22