Caleb Porzio

Using Babel Without The Build (Inline JS FTW!!!)

Sep 2019

Instead of reaching for Vue or React, I first see if I can solve my UI needs with plain old CSS (on top of Tailwind of course) and JavaScript. You can get a lot farther with them nowadays than you could back in the day.

If I need to do something small, I'll typically add a little inline <script> tag and just do it right there.

For example, let's show an alert message when a user clicks a button.

<script>
  var button = document.querySelector('button')

  button.addEventListener('click', () => {
    alert('You Clicked Me!')
  })
</script>

Notice my use of ES6 arrow functions for the click handler. This is fine in most modern browsers, but in lots of apps I work on, it's important to support legacy browsers like IE 11.

This is the biggest pitfall of this approach. If I were writing this bit of code in a more robust JavaScript build setup (like laravel-mix), Babel would automatically transpile this arrow function so older browsers will recognize it.

If you, like me, aren't willing to give up the simplicity of sprinkling JS inside script tags around your app. Here's a solution:

Add the following two files from a CDN to the <head> section of your page:

  <script src="https://unpkg.com/@babel/[email protected]/dist/polyfill.min.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

Now specify text/babel as the type of the script tag from before:

<script type="text/babel">
  var button = document.querySelector('button')

  button.addEventListener('click', () => {
    alert('You Clicked Me!')
  })
</script>

This tells Babel to transpile and process the JavaScript inside these tags. This code will now run on browsers as old as IE 11.

If you're interested in more info (adding babel configuration, using plugins, etc...), you can check out the docs page: https://babeljs.io/docs/en/babel-standalone

Note: Babel will throw a warning that you shouldn't be using this in a production context. Your JavaScript will be slower because it's not pre-transpiled. I personally am not worried about the speed loss for my use cases, but definitely something to note.

Another Note: I use Blade stacks to group my JavaScript snippets in the <head> or the bottom of the <body> tag. Otherwise, they will interrupt the page rendering.

Hope you found this helpful,


My Newsletter

I send out an email every so often about cool stuff I'm working on or launching. If you dig, go ahead and sign up!