From 1e1ff706b0291e5013538750b8cdd33a3b59eaea Mon Sep 17 00:00:00 2001 From: Nipinium Date: Sat, 7 Mar 2020 01:27:43 +0700 Subject: [PATCH] Add query string versioning for static assets in build process --- src/api/build.ts | 4 +++- src/api/utils/add_version_to_assets.ts | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 src/api/utils/add_version_to_assets.ts diff --git a/src/api/build.ts b/src/api/build.ts index c1bac879e..98d10c0d6 100644 --- a/src/api/build.ts +++ b/src/api/build.ts @@ -9,6 +9,7 @@ import { noop } from './utils/noop'; import validate_bundler from './utils/validate_bundler'; import { copy_runtime } from './utils/copy_runtime'; import { rimraf, mkdirp } from './utils/fs_utils'; +import add_version_to_assets from "./utils/add_version_to_assets"; type Opts = { cwd?: string; @@ -59,7 +60,7 @@ export async function build({ // minify src/template.html // TODO compile this to a function? could be quicker than str.replace(...).replace(...).replace(...) - const template = read_template(src); + let template = read_template(src); // remove this in a future version if (template.indexOf('%sapper.base%') === -1) { @@ -68,6 +69,7 @@ export async function build({ throw error; } + template = add_version_to_assets(template, static_files); fs.writeFileSync(`${dest}/template.html`, minify_html(template)); const manifest_data = create_manifest_data(routes, ext); diff --git a/src/api/utils/add_version_to_assets.ts b/src/api/utils/add_version_to_assets.ts new file mode 100644 index 000000000..939198083 --- /dev/null +++ b/src/api/utils/add_version_to_assets.ts @@ -0,0 +1,18 @@ +import * as fs from 'fs'; +import * as path from 'path'; +import hash from 'string-hash'; + +export default function inject_version_to_template_assets(template: string, static_files: string) { + const files = fs.readdirSync(static_files); + for (const file of files) { + const filePath = path.join(static_files, file); + + if (template.includes(file) && fs.existsSync(filePath)) { + const hashedInt = hash(fs.readFileSync(filePath).toString()); + const hashedStr = hashedInt.toString(16); + template = template.replace(file, `${file}?v=${hashedStr}`); + } + } + + return template; +}