usabilityhub / rails-erb-loader

Embedded Ruby (.erb) webpack loader for Ruby projects.
MIT License
103 stars 28 forks source link

Error: rails-erb-loader failed with code: 1 #63

Open Swat123 opened 6 years ago

Swat123 commented 6 years ago

Running the following: ruby -e $stdout.sync=true;$stderr.sync=true;load($0=ARGV.shift) /Users/swathishah/shopify-app/bin/spring rails --trace assets:precompile

But I randomly get following error:

ERROR in ./app/javascript/components/layout_tab.js.erb
Module build failed: Error: rails-erb-loader failed with code: 1
    at ChildProcess.<anonymous> (/Users/swathishah/shopify-app/node_modules/rails-erb-loader/index.js:108:16)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:191:7)
    at maybeClose (internal/child_process.js:886:16)
    at Socket.<anonymous> (internal/child_process.js:342:11)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at Pipe._handle.close [as _onclose] (net.js:501:12)
 @ ./app/javascript/components/tabs.js 12:0-44
 @ ./app/javascript/packs/notifications_react.jsx

Package.json has following:

{
  "name": "shopify-app",
  "private": true,
  "dependencies": {
    "@rails/webpacker": "^3.2.1",
....
   "rails-erb-loader": "^5.4.1",
...
    "yarn": "^1.3.2"
  },
  "devDependencies": {
    "webpack-dev-server": "^2.11.1"
}
type-face commented 6 years ago

Our issue was also related to spring, but running GitLab pipelines. Had to run bundle install --without development on our pipeline job to get it to work.

skatkov commented 5 years ago

I had a similar issue with one of the projects I'm working on (rails based).

None of the solutions mentioned here worked for us, so I went into debugging mode... and found a commit that broke everything.

I managed to downgrade some of the gems, not sure which gem exactly broke rails-erb-loader -- but my best bet is autoprefixer-rails (locked to 9.6.1.1) or rails-html-sanitizer ( locked to 1.2.0).

PikachuEXE commented 5 years ago

@skatkov I use both of them fully updated

ash106 commented 4 years ago

Is there no way to rename application.js to application.js.erb with this software?? It works fine with the example but I'm trying to use it to import gems in my application.js, not import other js files with erb in them. It looks like it did work at some point according to this comment: https://github.com/nathanvda/cocoon/issues/452#issuecomment-384836675. Is this not a thing anymore? All I get is this useless error message.

Screen Shot 2020-02-07 at 11 18 12 AM Screen Shot 2020-02-07 at 11 20 24 AM
margalit commented 4 years ago

In my instance, this error was due to a ruby version bump which was identified easily as @rhys-vdw pointed out after running: bin/rails runner.

rept commented 4 years ago

I have the same issue, very annoying.

ERROR in ./app/javascript/packs/serviceworker.js.erb
Module build failed (from ./node_modules/rails-erb-loader/index.js):
Error: rails-erb-loader failed with code: 1
    at ChildProcess.<anonymous> (/home/app/webapp/node_modules/rails-erb-loader/index.js:128:16)
    at ChildProcess.emit (events.js:198:13)
    at maybeClose (internal/child_process.js:982:16)
    at Socket.stream.socket.on (internal/child_process.js:389:11)
    at Socket.emit (events.js:198:13)
    at Pipe._handle.close (net.js:607:12)

I tried setting DISABLE_SPRING as well as NODE_ENV as indicated in this thread, to no avail.

This is my erb.js file:

module.exports = {
  test: /\.erb$/,
  enforce: 'pre',
  exclude: /node_modules/,
  use: [{
    loader: 'rails-erb-loader',
    options: {
      runner: 'bin/rails runner',
      env: { DISABLE_SPRING: 1, NODE_ENV: 'development' }
    }
  }]
}

I've also tried without the env and with preceding the DISABLE_SPRING to the runner.

I'm using version 5.5.2

For completeness this is the serviceworker.js.erb file:

var CACHE_VERSION = 'v10'; var CACHE_NAME = CACHE_VERSION + ':sw-cache-';

function onInstall(event) {
  console.log('[Serviceworker]', "Installing!", event);
  event.waitUntil(
    caches.open(CACHE_NAME).then(function prefill(cache) {
      return cache.addAll([
        <% helpers = ActionController::Base.helpers %>
        '<%= helpers.asset_pack_path "application.js" %>',
        '<%= helpers.asset_path "application.css" %>',
        '<%= helpers.asset_path "mobile.css" %>',
        '/icons/icon-white-24x24.png',
        '/icons/icon-24x24.png',
        '/icons/icon-96x96.png',
        '/apple-touch-icon.png',
        '/offline-notice.html'
      ]);
    })
  );
}

function onActivate(event) {
  console.log('[Serviceworker]', "Activating!", event);
  event.waitUntil(
    caches.keys().then(function(cacheNames) {
      return Promise.all(
        cacheNames.filter(function(cacheName) {
          // Return true if you want to remove this cache,
          // but remember that caches are shared across
          // the whole origin
          return cacheName.indexOf(CACHE_VERSION) !== 0;
        }).map(function(cacheName) {
          return caches.delete(cacheName);
        })
      );
    })
  );
}

// Borrowed from https://github.com/TalAter/UpUp
function onFetch(event) {
  event.respondWith(
    // try to return untouched request from network first
    fetch(event.request).catch(function() {
      // if it fails, try to return request from the cache
      return caches.match(event.request).then(function(response) {
        if (response) {
          return response;
        }
        // if not found in cache, return default offline content for navigate requests
        if (event.request.mode === 'navigate' ||
          (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
          console.log('[Serviceworker]', "Fetching offline content", event);
          return caches.match('/offline-notice.html');
        }
      })
    })
  );
}

self.addEventListener("push", function (event) {
    var title = event.data.json()['title'];
    var body = event.data.json()['body'];
    var tag = event.data.json()['tag'] || '';
    var icon = event.data.json()['icon'] || '';
    var sound = event.data.json()['sound'] || '';
    var image = event.data.json()['image'] || '';
    var actions = event.data.json()['actions'] || [];
    var badge = '/icons/icon-white-24x24.png';
    var data = event.data.json()['data'] || {};
    event.waitUntil(self.registration.showNotification(title, {
        body: body,
        icon: icon,
        badge: badge,
        sound: sound,
        image: image,
        actions: actions,
        data: data,
        vibrate: [500,110,500,110,450,110,200,110,170,40,450,110,200,110,170,40,500],
        tag: tag
    }));
});

self.addEventListener('notificationclick', function(event) {
    console.log('[Nobi] Notification click Received.');
    event.waitUntil(
      clients.openWindow(event.notification.data['link'])
    );
});

self.addEventListener('install', onInstall);
self.addEventListener('activate', onActivate);
self.addEventListener('fetch', onFetch);

The webpack-dev-server is running fine, it's only when deploying to production this is giving issues.

tfwright commented 4 years ago

In case it helps someone else having this issue, it was happening to me when trying to deploy to heroku using ../bin/rails runner for the runner option. Along the lines of the suggestion in https://github.com/usabilityhub/rails-erb-loader/issues/63#issuecomment-392746607 changing it to ../bin/bundle exec rails runner fixed the issue.

Yardboy commented 4 years ago

Just chiming in with my solution, for anyone that comes looking in the future. I ran into this issue trying to deploy a Rails 6 application to Dokku using ERB javascript templates. Everything worked great locally under development and production env settings, but when pushed to Dokku it would fail at the assets:precompile step. None of the solutions I found here or elsewhere solved the problem.

Ultimately, I discovered that my binstubs were not executable upon deploy. #fml

This was the error I was getting.

remote: events.js:174
remote:       throw er; // Unhandled 'error' event
remote:       ^
remote:
remote: Error: spawn bin/rails EACCES
remote:     at Process.ChildProcess._handle.onexit (internal/child_process.js:240:19)
remote:     at onErrorNT (internal/child_process.js:415:16)
remote:     at process._tickCallback (internal/process/next_tick.js:63:19)
remote: Emitted 'error' event at:
remote:     at Process.ChildProcess._handle.onexit (internal/child_process.js:246:12)
remote:     at onErrorNT (internal/child_process.js:415:16)
remote:     at process._tickCallback (internal/process/next_tick.js:63:19)
remote:
remote: The command '/bin/sh -c bundle exec rails assets:precompile' returned a non-zero code: 1
amkisko commented 4 years ago

Maybe add console.log here: https://github.com/usabilityhub/rails-erb-loader/blob/master/index.js#L93

  child.stdout.on('data', function (data) {
    console.log(data);
    dataBuffers.push(data);
  })

Would be good to have options: { debug: true } that turns on verbose logging like printing dataBuffers.

https://github.com/usabilityhub/rails-erb-loader/pull/83

mcmaddox commented 4 years ago

FWIW, I resolved this issue by correcting a Zeitwork::NameError thrown while deploying to Heroku (Rails 6.0.3; Ruby 2.7.1p83; WSL [Ubuntu 18.04]) :

`on_file_autoloaded': expected file /tmp/build_10e9581d550a3c3f1134ca4159ab62d0/app/controllers/admins/[snake_case].rb to define constant Admins::[CamelCase], but didn't (Zeitwerk::NameError)

My fix was simple: For each file that caused this error, I pluralized the module name (e.g., "Admins" instead of "Admin") to resolve the error.

I'm not sure if there is a conflict between Zeitwork and rails-erb-loader, but this resolved compilation errors for TWO failing js.erb files.

MtnBiker commented 4 years ago

Not sure another me too will help; but the error is in a new simple app in development mode. Here are all the gems including ones from development mode which I'm in. Using webpacker for JS and SCSS, but not for images.

A new small tutorial app. But I wanted <%= icon("icons8-marker-48.png") %> in maps.js.erb

ruby '2.7.0'
gem 'rails', '~> 6.0.3', '>= 6.0.3.2'
gem 'pg', '>= 0.18', '< 2.0'
gem 'puma', '~> 4.1'
gem 'jbuilder', '~> 2.7'
gem 'webpacker'
gem 'bootsnap', '>= 1.4.2', require: false
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
gem 'web-console', '>= 3.3.0'
gem 'listen', '~> 3.2'
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

And

yarn add @rails/webpacker
rails webpacker:install
yarn add rails-erb-loader
yarn add ol // openlayers which is what the tutorial is about

Error in localhost:

bootstrap:83 Uncaught Error: Module build failed (from /Users/gscar/node_modules/rails-erb-loader/index.js):
Error: rails-erb-loader failed with code: 1
    at ChildProcess.<anonymous> (:3000/Users/gscar/node_modules/rails-erb-loader/index.js:128)
    at ChildProcess.emit (:3000/events.js:314)
    at maybeClose (:3000/internal/child_process.js:1047)
    at Socket.<anonymous> (:3000/internal/child_process.js:438)
    at Socket.emit (:3000/events.js:314)
    at Pipe.<anonymous> (:3000/net.js:672)
    at Object../app/javascript/packs/maps.js.erb (bootstrap:83)
    at __webpack_require__ (bootstrap:19)
    at bootstrap:83
    at bootstrap:83
./app/javascript/packs/maps.js.erb @ bootstrap:83
__webpack_require__ @ bootstrap:19
(anonymous) @ bootstrap:83
(anonymous) @ bootstrap:83

Without the erb in the js script page loads fine.

rhys-vdw commented 4 years ago

@MtnBiker are you sure the actual error isn't being printed out further up the build output? In any case I'd strongly advise against using this tool in a new stack, rails-erb-loader was designed as a stopgap for if you have legacy ERB from a sprockets project that is now being built w/ webpack. There are better ways to get image paths into your JS that don't require templating. Read the guide.

MtnBiker commented 4 years ago

@rhys-vdw Not sure about your first sentence. The error I showed is the only error in Chrome Console.

But I'll take your advice. Many recommended against handling images with Webpacker, but I guess I'm pushing the limits, so will dive in. Part of it is the changing recommendations and to start with I don't have a webpack.config.js in my project. I realize Rails handles these things differently but it's more to wade through. And Rails guides hasn't caught up.

Thank you for answering.

EDIT for others as lacking in knowledge as I appears rails-erb-loader is added anyway, but .erb is not needed AFAIK.

rhys-vdw commented 4 years ago

@MtnBiker

Not sure about your first sentence. The error I showed is the only error in Chrome Console.

When you run webpack normally it just spits output into the console, and any error from the rails-erb-loader process is piped out to STDERR before the exception is fired. I can't recall if this output it included in Chrome.

Many recommended against handling images with Webpacker

I can't comment on webpacker, it's a gem that relies on this module but I've never used it. It's very normal to require images with webpack itself though, just don't use this module for it. rails-erb-loader is very slow and error-prone, and needlessly heavy handed for that task. Furthermore ERB prevents your JS from being statically analysed by linters, prettier and other code tools.

Part of it is the changing recommendations and to start with I don't have a webpack.config.js in my project.

My guess is that webpacker would be set up to handle images via image-loader (it's a built-in package). Try require()ing an image path from your source folder and it should work. I've never had a project that doesn't require modification of the webpack config, might want to look into how to get access to it šŸ¤·.

ethonlyup commented 4 years ago

I get this error message when attempting to compile a .js.erb file with webpacker.

`ERROR in ./app/javascript/packs/freelancer.js.erb Module build failed (from ./node_modules/rails-erb-loader/index.js): Error: rails-erb-loader failed with code: 1 
at ChildProcess.<anonymous> (/mnt/c/Code/helloworld/node_modules/rails-erb-loader/index.js:128:16) 
at ChildProcess.emit (events.js:198:13) 
at maybeClose (internal/child_process.js:982:16) 
at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5) (erb):12:in

': undefined method render' for main:Object (NoMethodError) from /home/ben/.rbenv/versions/2.6.5/lib/ruby/2.6.0/erb.rb:901:in eval'
from /home/ben/.rbenv/versions/2.6.5/lib/ruby/2.6.0/erb.rb:901:in result' from /mnt/c/Code/helloworld/node_modules/rails-erb-loader/erb_transformer.rb:20:in '`

My erb.js file looks like this.

`module.exports = { test: /\.erb$/, enforce: 'pre', exclude: /node_modules/, use: [{ loader: 'rails-erb-loader', options: { runner: (/^win/.test(process.platform) ? 'ruby ' : '') + 'bin/rails runner', env: { ...process.env, DISABLE_SPRING: 1, }, }, }], }`

I've tried a few solutions here, involving changing the path to 'ruby bin\ rails runner' since I'm on a windows machine, if I do that I get this error

'Error: spawn DISABLE_SPRING=1 ENOENT erb-rails-loader'.

I've tried adding

'options: { runner: 'DISABLE_SPRING=1 bin/rails runner' }'

same ENOENT error.

I've tried adding the below snippet to erb.js, same exit code: 1

engine: { name: 'erubis', includes: [ 'ActionView::Helpers', 'Rails.application.routes.url_helpers' ] }

I've also tried adding the helper in my transformer_erb file like such require 'erb' include Rails.application.routes.url_helpers ERB

To no avail, not sure where to go from here. For context, i'm on WSL 2 running ubuntu 16.

I've isolated my compiling error to these two lines of code.

$('#records_table').append("<%= j(render 'partials/gallery_items')%>"); $('#div_next_link').html("<%= j(render 'partials/next_link') %>");

n-rodriguez commented 4 years ago

I'm commenting on https://github.com/usabilityhub/rails-erb-loader/issues/63#issuecomment-647127581 but it should be a starter for anyone who has issues with rails-erb :

I'm not sure if there is a conflict between Zeitwork and rails-erb-loader, but this resolved compilation errors for TWO failing js.erb files.

It's not a conflict but the thing is : rails-erb-loader calls the rails runner command (https://guides.rubyonrails.org/command_line.html#rails-runner) to generate JS from js.erb templates.

What it says:

runner runs Ruby code in the context of Rails non-interactively

So your app must be fully functionnal before calling rake assets:precompile in any environment.

To be sure: run your app locally but in production mode (rails -e production). If you have some issues here (Rails don't start because of Zeitwerk or any other issues like environment variables) rake assets:precompile will surely fail later. It also means that your view.js.erb file must contain valid Ruby/Rails code or it will fail too.

Technically what it does is :

# something like that
cat myfile | bin/rails runner <path to erb_transformer.rb> > output.js

https://github.com/usabilityhub/rails-erb-loader/blob/master/index.js#L21 https://github.com/usabilityhub/rails-erb-loader/blob/master/index.js#L75 https://github.com/usabilityhub/rails-erb-loader/blob/master/erb_transformer.rb

You can even try it manually :)

rhys-vdw commented 4 years ago

Thanks for detailed response @n-rodriguez. This is correct (but you also need to pass "engine" and "delimiter" arguments to the erb_transformer.)

@yosupgurl In this case though there are no real surprises here (for me, the author of this module). You're hitting issue #33. The runner doesn't add anything to scope. You'll see that error if you're trying to call a function render which is not available. I don't know how to do what you're doing, but there is some discussion in #33 you can refer to.

We always used render at runtime for serving requests, not for baking HTML into JS strings at build time. Are you sure that's even a good idea? Why not just inline the HTML straight into this file. Basically if you want to use webpack then you shouldn't be using render and partial, that's the point. Use raw-loader on a HTML file or something.

Also same general advice I gave above: This is not a good tool for web development, it's a transitional tool for moving away from server-side helpers and into SPA land using the superior webpack system. It's slow and bad and should really be used as minimally as possible (until someone volunteers some fixes).

ethonlyup commented 4 years ago

@rhys-vdw I'm using pagy to paginate a list of items. I'm initializing the variable that contains the paginated list before I call the j render function, this should allow for this functionality, no?

Sorry, I'm fairly new to web dev and I've been stuck on this for quite some time. None of the solutions allow me to properly render the paginated partial on click. Perhaps you could link me to a resource that would allow me to implement this feature?

mattwd7 commented 4 years ago

@mcmaddox and @n-rodriguez saved me on this in the end. Despite Error: rails-erb-loader failed with code: 1 higher up in my logs, it was the Zeitwork error further down that was the root of the issue. In my case, I needed to rename/remove compiled directory names beginning with a number to make Zeitwork happy, which was pretty explicit in the error logging...!

ALSO, for anyone coming here on a ModuleNotFoundError on their rails-erb-loader, check your package.json!! Following the instructions in the rails-erb-loader Readme will have you adding the module in your devDependencies which is invisible to your production env :(

For a good time, add rails-erb-loader as a standard dependency, not a devDependency.

rcerqueira-dv commented 3 years ago

Hello everyone, any updates on this problem?

"rails-erb-loader": "^5.5.2"

my erb.js

/* put this in file like /config/webpack/loaders/erb.js */
/* global process:false */

module.exports = {
  test:     /\.erb$/,
  enforce:  "pre",
  exclude:  /node_modules/,

  use: [{
    loader:   "rails-erb-loader",
    options:  {
      timeoutMs: 20000,
      runner:     (/^win/.test(process.platform) ? "ruby " : "") + "bin/rails runner",
      env:        {
        ...process.env,
        DISABLE_SPRING: 1,
      },
    },
  }],
}

My output on precompile, compile webpacker

image

rhys-vdw commented 3 years ago

I think I made this change to force Ruby to output the error, but it never got merged. You could try making that modification to your erb_transformer.rb file and see if it prints your error.

cassioalmeidas commented 3 years ago

I'm having the same problem on heroku with rails 6.1, it compiles with command RAILS_ENV=production assets:precompile on my machine, but when pushing to heroku the following error is displayed:

       ERROR in ./app/javascript/i18n-js/index.js.erb
        Module build failed (from ./node_modules/rails-erb-loader/index.js):
        Error: rails-erb-loader failed with code: 1
            at ChildProcess. (/tmp/build_4d3416a8/node_modules/rails-erb-loader/index.js:128:16)
            at ChildProcess.emit (events.js:375:28)
            at maybeClose (internal/child_process.js:1055:16)
            at Socket. (internal/child_process.js:441:11)
            at Socket.emit (events.js:375:28)
            at Pipe. (net.js:675:12)
         @ ./app/javascript/packs/application.js 5:392-431 5:443-447 5:448-452 

        ERROR in ./app/javascript/packs/hello_erb.js.erb
        Module build failed (from ./node_modules/rails-erb-loader/index.js):
        Error: rails-erb-loader failed with code: 1
            at ChildProcess. (/tmp/build_4d3416a8/node_modules/rails-erb-loader/index.js:128:16)
            at ChildProcess.emit (events.js:375:28)
            at maybeClose (internal/child_process.js:1055:16)
            at Socket. (internal/child_process.js:441:11)
            at Socket.emit (events.js:375:28)
            at Pipe. (net.js:675:12)

rcerqueira-dv commented 3 years ago

In my case is while doing the docker image, could it be the same problem in heroku, because without the DISABLE_SPRING the problem is that ruby does not exists in the linux machine that im creating the docker, but thats the thing, it should not need ruby outside the docker to use ruby inside the docker

cassioalmeidas commented 3 years ago

@rcerqueira11AP I've already set DISABLE_SPRING=1 in heroku's environment variables, but it didn't do any good

jwoodrow commented 3 years ago

I had this issue with a PR that changed both the ruby version and rails version to ruby 3.0.1 and rails 6.1.3.2 that kept failing only on Travis.

After a lot of debugging I found that my error was FATAL: Listen error: unable to monitor directories for changes so after adding this to my travis.yml my assets:precompile started working again šŸŽ‰

before_script:
  - echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

maybe this can help someone else having the same issues because this thread had me thinking it was a spring problem but in my case it was not since it's working without any DISABLE_SPRING=1

0xradical commented 3 years ago

After running webpack on a heroku bash session, I found out that there's something odd going on with the ARGV being passed to bin/rails...

/app/app/node_modules/rails-erb-loader/erb_transformer.rb:13:in `<top (required)>': Unknown templating engine `__RAILS_ERB_LOADER_DELIMETER__` (RuntimeError)

It seems the process is receiving the following ARGV, which is logically incorrect per erb_transformer.rb

["/app/node_modules/rails-erb-loader/erb_transformer.rb", "__RAILS_ERB_LOADER_DELIMETER__", "erb"]

I think this is due to the eager loading that happens on production, for some reason app/node_modules is an eager loaded path and when it tries to load the erb_transformer.rb file, it blows up ...

cassioalmeidas commented 3 years ago

@thiagobrandam see how i solved my problem https://github.com/jbox-web/ajax-datatables-rails/issues/394

lcampanari commented 3 years ago

I ran into an issue that exemplifies the following statement given by @n-rodriguez, and wanted to highlight it.

So your app must be fully functionnal before calling rake assets:precompile in any environment.

On dev environment the erb-loader was working fine. The issue would appear only when deploying to Heroku review apps. The logs would show

Module build failed: Error: rails-erb-loader failed with code: 1

for all .js.erb files, and further down there was also other database errors that seemed unrelated:

PG::UndefinedTable: ERROR:  relation "xxx" does not exist (ActiveRecord::StatementInvalid)

After hours of debugging, we found out that bin/rails runner was trying to load database dependencies when the db had no schema loaded yet. On Heroku review apps the assets:precompile is executed on the build phase, while db:schema:load is executed on post-deploy.

I couldn't find a way to overcome that by changing Heroku deploy configs. The solution was to remove this gem and use asset pipeline setup for this specific use case šŸ˜”. If anyone knows another solution for this please let me know. Thanks!

rhys-vdw commented 3 years ago

After hours of debugging, we found out that bin/rails runner was trying to load database dependencies when the db had no schema loaded yet.

So this module will just do whatever happens when you call rails runner. If that depends on your schema then it'll have to be there. It's an unfortunate design choice of ActiveRecord that it reads your schema at startup, compounded with the unfortunate design of Rails loading up every single object at startup.

However do you need to transpile your JS at this stage? Surely your backend doesn't rely on JS being compiled. Just run webpack as the last step after your database has been migrated.

The solution was to remove this gem and use asset pipeline setup for this specific use case šŸ˜”.

This is not a gem, it's an npm package. If your issue is with webpacker, as opposed to this package, please raise issues there. I am not in control of how it's integrated in other packages. rails-erb-loader predates webpacker.

Might I add that this was created so that we could stop using assets:precompile and develop our app as an SPA using webpack. rails-erb-loader should be treated as a necessary evil to migrate a codebase away from Rails asset pipeline, not as a permanent part of your stack. It's not particularly good, but it'll save you migrating your old erb files over in one go. There are better options available for templating your front end dependencies that do not require Rails at all. The simplest of these is simply storing your shared constants in a JSON file that is read by both json-loader and Rails itself at startup.

sudoudaisuke commented 2 years ago

I tryied same error. I got this error message. I think that "runner_command.rb:46" can not find a file (or not exist). The erbtransformer.rb file path is under ".yarn/__virtual_\/". Why rails-erb-loader can not find the file?

I created repro this Dockerfile.zip.

not found filename

/web/.yarn/__virtual__/rails-erb-loader-virtual-27b0bedac7/0/cache/rails-erb-loader-npm-5.5.2-8c1ad94c6e-f89ac4f14b.zip/node_modules/rails-erb-loader/erb_transformer.rb

error message

#yarn build
Please specify a valid ruby command or the path of a script to run.
Run 'rails runner -h' for help.

/web/vendor/bundle/ruby/3.1.0/gems/railties-7.0.3/lib/rails/commands/runner/runner_command.rb:46: syntax error, unexpected local variable or method, expecting end-of-input
...s-erb-loader-virtual-27b0bedac7/0/cache/rails-erb-loader-npm...
...                       ^~~~~~~~
assets by status 1.05 KiB [cached] 1 asset
runtime modules 663 bytes 3 modules
cacheable modules 63 bytes
  ./app/javascript/app.js 24 bytes [built] [code generated]
  ./app/javascript/myerb.js.erb 39 bytes [built] [code generated] [1 error]

ERROR in ./app/javascript/myerb.js.erb
Module build failed (from ./.yarn/__virtual__/rails-erb-loader-virtual-27b0bedac7/0/cache/rails-erb-loader-npm-5.5.2-8c1ad94c6e-f89ac4f14b.zip/node_modules/rails-erb-loader/index.js):
Error: rails-erb-loader failed with code: 1

webpack.config.js

  module: {
    rules: [
      {
        test: /\.erb$/,
        enforce: "pre",
        loader: "rails-erb-loader",
        options: {
          runner: "bundle exec bin/rails runner"
        }
      }
    ]
  },

environments

unRARed commented 2 years ago

Per @rhys-vdw's comment

I ran into an issue that exemplifies the following statement given by @n-rodriguez, and wanted to highlight it.

So your app must be fully functionnal before calling rake assets:precompile in any environment.

On dev environment the erb-loader was working fine. The issue would appear only when deploying to Heroku review apps. The logs would show

Module build failed: Error: rails-erb-loader failed with code: 1

for all .js.erb files, and further down there was also other database errors that seemed unrelated:

PG::UndefinedTable: ERROR:  relation "xxx" does not exist (ActiveRecord::StatementInvalid)

After hours of debugging, we found out that bin/rails runner was trying to load database dependencies when the db had no schema loaded yet. On Heroku review apps the assets:precompile is executed on the build phase, while db:schema:load is executed on post-deploy.

I couldn't find a way to overcome that by changing Heroku deploy configs. The solution was to remove this gem and use asset pipeline setup for this specific use case šŸ˜”. If anyone knows another solution for this please let me know. Thanks!

We ran into the same situation. For specifically this Heroku Review Apps + webpacker + rails-erb-loader issue, I think I solved by sort of monkey patching the Rake Task:

./lib/tasks/heroku_review_app_assets_precompile.rake

if ENV["RAILS_ENV"] == "review"
  Rake::Task["assets:precompile"].enhance(["db:schema:load"])
end

It does mean that rails db:schema:load happens twice, but seems like only a nit? Or maybe this is too naive?