about summary refs log tree commit diff
path: root/app/javascript/packs/public-path.js
diff options
context:
space:
mode:
authorThibG <thib@sitedethib.com>2020-10-13 01:19:35 +0200
committerGitHub <noreply@github.com>2020-10-13 01:19:35 +0200
commit4c45b43cb8a3d902c130729d36d559ec9de23d3e (patch)
treeee915a79950dbad38d515a8870a30e40480bff5e /app/javascript/packs/public-path.js
parent53b22d247fb8500ea977774d727fe0d41950189c (diff)
Change how CDN_HOST is passed down to make assets build reproducible (#14381)
* Change how CDN_HOST is passed down to make assets build reproducible

* Change webpacker/webpack configuration to dynamically load publicPath based on meta header

* Fix embedded layout missing the cdn-host meta header
Diffstat (limited to 'app/javascript/packs/public-path.js')
-rw-r--r--app/javascript/packs/public-path.js21
1 files changed, 21 insertions, 0 deletions
diff --git a/app/javascript/packs/public-path.js b/app/javascript/packs/public-path.js
new file mode 100644
index 000000000..f96109f4f
--- /dev/null
+++ b/app/javascript/packs/public-path.js
@@ -0,0 +1,21 @@
+// Dynamically set webpack's loading path depending on a meta header, in order
+// to share the same assets regardless of instance configuration.
+// See https://webpack.js.org/guides/public-path/#on-the-fly
+
+function removeOuterSlashes(string) {
+  return string.replace(/^\/*/, '').replace(/\/*$/, '');
+}
+
+function formatPublicPath(host = '', path = '') {
+  let formattedHost = removeOuterSlashes(host);
+  if (formattedHost && !/^http/i.test(formattedHost)) {
+    formattedHost = `//${formattedHost}`;
+  }
+  const formattedPath = removeOuterSlashes(path);
+  return `${formattedHost}/${formattedPath}/`;
+}
+
+const cdnHost = document.querySelector('meta[name=cdn-host]');
+
+// eslint-disable-next-line camelcase, no-undef, no-unused-vars
+__webpack_public_path__ = formatPublicPath(cdnHost ? cdnHost.content : '', process.env.PUBLIC_OUTPUT_PATH);