Skip to content
This repository was archived by the owner on Jan 11, 2023. It is now read-only.

Add query string versioning for static assets in build process #1109

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/api/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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) {
Expand All @@ -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);
Expand Down
18 changes: 18 additions & 0 deletions src/api/utils/add_version_to_assets.ts
Original file line number Diff line number Diff line change
@@ -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;
}