How to Compile Ruby to JavaScript

Compile an opalized Ruby gem to Node package

We are currently in a process of designing a good NPM integration. But as of now, yes. You can build an Opal project to a .js (or .mjs) file and require it in the Node environment.

One issue though: Opal does not behave well in the JS environment, as it defines globals, modifies prototypes, etc. - it may cause a mess, though most incompatibilities have been sorted out over the years (in any case, you may consider running Opal code in a WebWorker). The main issue here is that such a package will inadvertently include opal corelib - and you should take care to include it just once. So, your Opal part of the application should be compiled together, not split together into multiple packages. We will work on correcting that issue in the following months.

As for interfacing Opal from JS, you should take a look at this: https://github.com/opal/opal/blob/master/docs/compiled_ruby.md#ruby-from-javascript

Production usage of compiling Ruby Red to javascript

The lack of response is response enough. Sadly.

Javascript compilation in Ruby on Rails 6

If you are using webpacker and you want to include js files in your views/layouts then you have to use javascript_pack_tag. All these files (called entries) should be under /packs (or where you set the source_path & source_entry_path in your webpacker.yml). The entries should import or require different files (bundle them) then webpacker will prepare them to be browser ready (babel, loaders, transpiling, etc..)

Create app/javascript/packs/test.js and add these:

 require('app/assets/javascripts/test.js')

This should fix the complilation issue. Webpacker has resolved_paths: [] in webpacaker.yml where you can add different paths to look for files. You can add app/assets/javascripts and change to:

require('test.js')

Now clicking that button. If you want to do it that way then test() should be on window. Another option is to bind an onClick event for that button at document ready. There are other options but these 2 are the easy ones.



Related Topics



Leave a reply



Submit