Skip to content

Commit

Permalink
Consolidate hydration scripts into just one (withastro#3571)
Browse files Browse the repository at this point in the history
* Remove redundant hydration scripts

* Prebuild the island JS

* Fix build

* Updates to tests

* Update more references

* Custom element test now has two classic scripts

* Account for non-default exports

* Restructure hydration directives

* Move nested logic into the island component

* Remove try/catch
  • Loading branch information
matthewp authored Jun 15, 2022
1 parent 2a2cc99 commit 7cb37f0
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
52 changes: 52 additions & 0 deletions cmd/prebuild.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import * as terser from 'terser';
import esbuild from 'esbuild';
import glob from 'tiny-glob';
import fs from 'fs';
import path from 'path';
import { pathToFileURL, fileURLToPath } from 'url';

export default async function prebuild(...args) {
let buildToString = args.indexOf('--to-string');
if(buildToString !== -1) {
args.splice(buildToString, 1);
buildToString = true;
}

let patterns = args;
let entryPoints = [].concat(
...(await Promise.all(
patterns.map((pattern) => glob(pattern, { filesOnly: true, absolute: true }))
))
);

function getPrebuildURL(entryfilepath) {
const entryURL = pathToFileURL(entryfilepath);
const basename = path.basename(entryfilepath);
const ext = path.extname(entryfilepath);
const name = basename.slice(0, basename.indexOf(ext));
const outname = `${name}.prebuilt${ext}`;
const outURL = new URL('./' + outname, entryURL);
return outURL;
}

async function prebuildFile(filepath) {
const tscode = await fs.promises.readFile(filepath, 'utf-8');
const esbuildresult = await esbuild.transform(tscode, {
loader: 'ts',
minify: true
});
const rootURL = new URL('../../', import.meta.url);
const rel = path.relative(fileURLToPath(rootURL), filepath)
const mod = `/**
* This file is prebuilt from ${rel}
* Do not edit this directly, but instead edit that file and rerun the prebuild
* to generate this file.
*/
export default \`${esbuildresult.code.trim()}\`;`;
const url = getPrebuildURL(filepath);
await fs.promises.writeFile(url, mod, 'utf-8');
}

await Promise.all(entryPoints.map(prebuildFile));
}
5 changes: 5 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ export default async function run() {
await copy(...args);
break;
}
case 'prebuild': {
const { default: prebuild } = await import('./cmd/prebuild.js');
await prebuild(...args);
break;
}
}
}

Expand Down

0 comments on commit 7cb37f0

Please sign in to comment.