Transpile ES6+ code (Babel & co)

I have “a few” JS lines of code in my custom Hugo theme. The problem with this code is that I’m forced to write ancient (ES5) JS to make sure that it’s as backwards compatible as possible. With Hugo v0.70 and its Babel support I hoped that I could write modern JS and transpile it into ES5, and it kind of works: syntax like arrow functions are transformed and requires/imports to core-js polyfills are included by Babel. The problem is that I’m unable to bundle it, as it seems that webpack/rollup/etc is needed for this matter, and none of them are supported by Hugo.

Am I right so far? I know that I could do something similar to what gohugoioTheme does: install webpack in that repo, build the bundle, commit it to the repo, and reference the bundle (and not the original files) from the template. But I haven’t need webpack for anything else and I’d love to have a modern JS experience with Hugo as good as the one with SCSS.

I just saw @bep 's Add JavaScript Modules support issue, which is somehow related with this matter (but it wouldn’t solve it, AFAIK) and wanted to share my use case.

I’d love to see Hugo handle (compile) ES6+ code out of the box as it does with SCSS :smiley:

You are mostly correct. We (or I) have not have the time to write a Webpack or Rollup replacement in Go … Which has meant that working with JS in Hugo has meant some level of pragmatism, which I think still is mostly worth it … Using resources.Concat to bundle your JS may be old fashioned, but it sure is fast…

It, for one, encourages you to keep the number of dependencies down. I have been fiddling with AlpineJS, which you can include via CDN or as a Hugo Module, see https://github.com/bep/hugo-jslibs/tree/master/alpinejs – you can get pretty far with that alone, and it avoids the situation where you pull all these plugins/libraries that you really don’t know the details of.

As to Babel, I think you can get pretty modern JS syntax without polyfills (if you don’t need IE 11 …). For polyfills there are other ways to include them, maybe

https://polyfill.io/v3/

2 Likes

Thanks a lot for the reply! It’s not a full solution to the problem I exposed but you gave me a few super interesting ideas to explore that route.

Thanks again! :smiley: