Skip to content

Passing ERB-templated variables to JS at app load? #135

Answered by ElMassimo
msakrejda asked this question in Q&A
Discussion options

You must be logged in to vote

If it's dynamic at startup, you could try using vite-plugin-erb. I don't recommend it though, it's slow as it requires calling Ruby from JS.

If the rendered data changes on every request, then the best approach is to ensure the rendered script is also type="module", get a reference to the main script that defines the callback using vite_asset_path, and inject an import script.

Pseudo code:

    <script type="module">
      import { foo } from '<%= vite_asset_path 'application.ts' %>'
      foo("<%= ENV.fetch('SOME_ENV_VAR', 'default') %>");
    </script>

Basically, you would leverage the wonderful ES Module system to ensure code is loaded in the correct order. Good bye ordering issues!

Som…

Replies: 1 comment 5 replies

Comment options

You must be logged in to vote
5 replies
@msakrejda
Comment options

@ElMassimo
Comment options

@msakrejda
Comment options

@ElMassimo
Comment options

@msakrejda
Comment options

Answer selected by ElMassimo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants