tooling.report

feature

Loading scripts

Can generated bundles be referenced from HTML?

Person in shorts with blue hair walking left

Introduction

When using a build tool to bundle or transform JavaScript, the resulting files generally have URLs that are different than those of the original modules they were constructed from. This come as a result of configurable output filename templating, or because the generated URLs contain hashes to enable long-term caching. In either case, it's important to be able to update <script> tags in an HTML document to reference the correct URLs for generated bundles.

The Test

This test bundles the scripts referenced by <script> tags in an HTML page. For tools that don't support using an HTML file as the "entry" for a build, a plugin is added that adds this functionality. The simple test page contains a single <script>, which should be replaced with its bundled URL.

index.html

<!DOCTYPE html>
<script src="./index.js"></script>

index.js

console.log('this is script');

After the build completes, two output files should be produced: a JavaScript bundle containing index.js, and a copy of index.html with the script's src updated to reference that bundle's hashed URL.

Conclusion

browserify

First, buildScripts task runs JS build with browserify, add hash, then produce manifest file, then replaceHTML task uses gulp-rev-collector plugin to replace src in respective HTML based on the manifest.

parcel
rollup

Non-JS entry points aren't natural for Rollup, but it's possible.

webpack

While html-webpack-plugin doesn't support ingesting HTML files and passing them through Webpack to compile, it is technically possible to write a loader that accomplishes this. The APIs for doing so are largely undocumented and it requires reaching into the compiler instance from a loader, which is not advised.