0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2024-12-16 21:46:22 -05:00

[ci] yarn format

This commit is contained in:
matthewp 2021-08-27 14:13:41 +00:00 committed by GitHub Actions
parent 788c769d78
commit 5cc7947a58
9 changed files with 65 additions and 69 deletions

View file

@ -281,7 +281,7 @@ By default Astro does not make any assumptions on how you want scripts to be ser
However if you'd like all of your scripts to be hoisted out of components and moved to the top of the page, and then later bundled together in production, you can achieve this with hoisted scripts.
A __hoisted script__ looks like this:
A **hoisted script** looks like this:
```astro
<script hoist>

View file

@ -140,7 +140,7 @@ ${stack}
const pageDeps = findDeps(buildState[id].contents as string, {
astroConfig,
srcPath: buildState[id].srcPath,
id
id,
});
depTree[id] = pageDeps;
@ -178,7 +178,7 @@ ${stack}
bundleCSS({ buildState, astroConfig, logging, depTree }).then(() => {
debug(logging, 'build', `bundled CSS [${stopTimer(timer.prebundleCSS)}]`);
}),
bundleHoistedJS({ buildState, astroConfig, logging, depTree, runtime: astroRuntime, dist: astroConfig.dist })
bundleHoistedJS({ buildState, astroConfig, logging, depTree, runtime: astroRuntime, dist: astroConfig.dist }),
// TODO: optimize images?
]);
// TODO: minify HTML?
@ -272,7 +272,7 @@ ${stack}
}
/** Given an HTML string, collect <link> and <img> tags */
export function findDeps(html: string, { astroConfig, srcPath }: { astroConfig: AstroConfig; srcPath: URL, id: string }): PageDependencies {
export function findDeps(html: string, { astroConfig, srcPath }: { astroConfig: AstroConfig; srcPath: URL; id: string }): PageDependencies {
const pageDeps: PageDependencies = {
js: new Set<string>(),
css: new Set<string>(),
@ -285,15 +285,15 @@ export function findDeps(html: string, { astroConfig, srcPath }: { astroConfig:
$('script').each((_i, el) => {
const src = $(el).attr('src');
const hoist = $(el).attr('data-astro') === 'hoist';
if(hoist) {
if(src) {
if (hoist) {
if (src) {
pageDeps.hoistedJS.set(src, {
src
src,
});
} else {
let content = $(el).html() || '';
pageDeps.hoistedJS.set(`astro-virtual:${hash.unique(content)}`, {
content
content,
});
}
} else if (src) {

View file

@ -6,7 +6,7 @@ import type { LogOptions } from '../../logger.js';
import { fileURLToPath } from 'url';
import { rollup } from 'rollup';
import { terser } from 'rollup-plugin-terser';
import { createBundleStats, addBundleStats, BundleStatsMap } from '../stats.js'
import { createBundleStats, addBundleStats, BundleStatsMap } from '../stats.js';
import { IS_ASTRO_FILE_URL } from '../util.js';
import cheerio from 'cheerio';
import path from 'path';
@ -35,7 +35,7 @@ export async function bundleHoistedJS({
logging,
depTree,
dist,
runtime
runtime,
}: {
astroConfig: AstroConfig;
buildState: BuildOutput;
@ -54,24 +54,26 @@ export async function bundleHoistedJS({
const virtualScripts = new Map<string, ScriptInfo>();
const pageToEntryMap = new Map<string, string>();
for(let pageUrl of sortedPages) {
for (let pageUrl of sortedPages) {
const hoistedJS = depTree[pageUrl].hoistedJS;
if(hoistedJS.size) {
for(let [url, scriptInfo] of hoistedJS) {
if(virtualScripts.has(url) || !url.startsWith('astro-virtual:')) continue;
if (hoistedJS.size) {
for (let [url, scriptInfo] of hoistedJS) {
if (virtualScripts.has(url) || !url.startsWith('astro-virtual:')) continue;
virtualScripts.set(url, scriptInfo);
}
const entryURL = pageUrlToVirtualJSEntry(pageUrl);
const entryJS = Array.from(hoistedJS.keys()).map(url => `import '${url}';`).join('\n');
const entryJS = Array.from(hoistedJS.keys())
.map((url) => `import '${url}';`)
.join('\n');
virtualScripts.set(entryURL, {
content: entryJS
content: entryJS,
});
entryImports.push(entryURL);
pageToEntryMap.set(pageUrl, entryURL);
}
}
if(!entryImports.length) {
if (!entryImports.length) {
// There are no hoisted scripts, bail
return;
}
@ -85,14 +87,13 @@ export async function bundleHoistedJS({
{
name: 'astro:build',
resolveId(source: string, imported?: string) {
if(virtualScripts.has(source)) {
if (virtualScripts.has(source)) {
return source;
}
if (source.startsWith('/')) {
return source;
}
if (imported) {
const outUrl = new URL(source, 'http://example.com' + imported);
return outUrl.pathname;
@ -101,12 +102,11 @@ export async function bundleHoistedJS({
return null;
},
async load(id: string) {
if(virtualScripts.has(id)) {
if (virtualScripts.has(id)) {
let info = virtualScripts.get(id) as InlineScriptInfo;
return info.content;
}
const result = await runtime.load(id);
if (result.statusCode !== 200) {
@ -128,8 +128,7 @@ export async function bundleHoistedJS({
entryFileNames(chunk) {
const { facadeModuleId } = chunk;
if (!facadeModuleId) throw new Error(`facadeModuleId missing: ${chunk.name}`);
return facadeModuleId.substr('astro-virtual:/'.length, facadeModuleId.length - 'astro-virtual:/'.length - 3 /* .js */)
+ '-[hash].js';
return facadeModuleId.substr('astro-virtual:/'.length, facadeModuleId.length - 'astro-virtual:/'.length - 3 /* .js */) + '-[hash].js';
},
plugins: [
// We are using terser for the demo, but might switch to something else long term
@ -146,7 +145,7 @@ export async function bundleHoistedJS({
const entryToChunkFileName = new Map<string, string>();
output.forEach((chunk) => {
const { fileName, facadeModuleId, isEntry } = chunk as OutputChunk;
if(!facadeModuleId || !isEntry) return;
if (!facadeModuleId || !isEntry) return;
entryToChunkFileName.set(facadeModuleId, fileName);
});
@ -161,7 +160,7 @@ export async function bundleHoistedJS({
const $ = cheerio.load(buildState[id].contents);
$('script[data-astro="hoist"]').each((i, el) => {
hasHoisted = true;
if(i === 0) {
if (i === 0) {
let chunkName = entryToChunkFileName.get(entryVirtualURL);
if (!chunkName) return;
let chunkPathname = '/' + chunkName;
@ -174,7 +173,7 @@ export async function bundleHoistedJS({
}
});
if(hasHoisted) {
if (hasHoisted) {
(buildState[id] as any).contents = $.html(); // save updated HTML in global buildState
}
});
@ -201,7 +200,6 @@ export async function bundleJS(imports: Set<string>, { astroRuntime, dist }: Bun
return source;
}
if (imported) {
const outUrl = new URL(source, 'http://example.com' + imported);
return outUrl.pathname;

View file

@ -673,14 +673,14 @@ async function compileHtml(enterNode: TemplateNode, state: CodegenState, compile
buffers[curr] += `h(__astro_slot_content, { name: ${attributes.slot} },`;
paren++;
}
if(attributes.hoist) {
if(attributes.src) {
if (attributes.hoist) {
if (attributes.src) {
state.hoistedScripts.push({
src: attributes.src.substr(1, attributes.src.length - 2)
src: attributes.src.substr(1, attributes.src.length - 2),
});
} else if(node.children && node.children.length === 1 && node.children[0].type === 'Text') {
} else if (node.children && node.children.length === 1 && node.children[0].type === 'Text') {
state.hoistedScripts.push({
content: node.children[0].data
content: node.children[0].data,
});
}
this.skip();

View file

@ -155,7 +155,7 @@ ${result.getStaticPaths || ''}
import { h, Fragment } from 'astro/dist/internal/h.js';
import { __astro_hoisted_scripts } from 'astro/dist/internal/__astro_hoisted_scripts.js';
const __astroScripts = __astro_hoisted_scripts([${result.components.map(n => `typeof ${n} !== 'undefined' && ${n}`)}], ${JSON.stringify(result.hoistedScripts)});
const __astroScripts = __astro_hoisted_scripts([${result.components.map((n) => `typeof ${n} !== 'undefined' && ${n}`)}], ${JSON.stringify(result.hoistedScripts)});
const __astroInternal = Symbol('astro.internal');
const __astroContext = Symbol.for('astro.context');
async function __render(props, ...children) {

View file

@ -138,9 +138,9 @@ export default function (opts: TransformOptions): Transformer {
{
type: 'Text',
raw: 'module',
data: 'module'
}
]
data: 'module',
},
],
},
{
type: 'Attribute',
@ -157,8 +157,8 @@ export default function (opts: TransformOptions): Transformer {
codeChunks: ['script.src'],
children: [],
},
}
]
},
],
},
{
type: 'Attribute',
@ -167,10 +167,10 @@ export default function (opts: TransformOptions): Transformer {
{
type: 'Text',
raw: 'hoist',
data: 'hoist'
}
]
}
data: 'hoist',
},
],
},
],
start: 0,
end: 0,
@ -187,9 +187,9 @@ export default function (opts: TransformOptions): Transformer {
{
type: 'Text',
raw: 'module',
data: 'module'
}
]
data: 'module',
},
],
},
{
type: 'Attribute',
@ -198,10 +198,10 @@ export default function (opts: TransformOptions): Transformer {
{
type: 'Text',
raw: 'hoist',
data: 'hoist'
}
]
}
data: 'hoist',
},
],
},
],
start: 0,
end: 0,
@ -217,11 +217,11 @@ export default function (opts: TransformOptions): Transformer {
codeChunks: ['script.content'],
children: [],
},
}
},
],
},
],
},
]
}
],
},
],

View file

@ -3,7 +3,7 @@ import type { ScriptInfo } from '../@types/astro';
const sym = Symbol.for('astro.hoistedScripts');
interface ComponentThatMaybeHasHoistedScripts {
[sym]: ScriptInfo[]
[sym]: ScriptInfo[];
}
/**
@ -14,16 +14,16 @@ interface ComponentThatMaybeHasHoistedScripts {
function hoistedScripts(Components: ComponentThatMaybeHasHoistedScripts[], scripts: ScriptInfo[]) {
const flatScripts = [];
const allScripts: ScriptInfo[] = Components.map(c => c && c[sym])
.filter(a => a)
const allScripts: ScriptInfo[] = Components.map((c) => c && c[sym])
.filter((a) => a)
.concat(scripts)
.flatMap(a => a);
.flatMap((a) => a);
const visitedSource = new Set();
for(let script of allScripts) {
if(!('src' in script)) {
for (let script of allScripts) {
if (!('src' in script)) {
flatScripts.push(script);
} else if(!visitedSource.has(script.src)) {
} else if (!visitedSource.has(script.src)) {
flatScripts.push(script);
visitedSource.add(script.src);
}
@ -32,6 +32,4 @@ function hoistedScripts(Components: ComponentThatMaybeHasHoistedScripts[], scrip
return flatScripts;
}
export {
hoistedScripts as __astro_hoisted_scripts
};
export { hoistedScripts as __astro_hoisted_scripts };

View file

@ -163,7 +163,7 @@ async function load(config: AstroRuntimeConfig, rawPathname: string | undefined)
children: [],
props: pageProps,
css: Array.isArray(mod.css) ? mod.css : typeof mod.css === 'string' ? [mod.css] : [],
scripts: mod.exports.default[Symbol.for('astro.hoistedScripts')]
scripts: mod.exports.default[Symbol.for('astro.hoistedScripts')],
})) as string;
return {

View file

@ -31,10 +31,10 @@ Scripts('Moves inline scripts up', async ({ runtime }) => {
assert.equal($('body script').length, 0);
});
Scripts('Builds the scripts to a single bundle', async({ build, readFile }) => {
Scripts('Builds the scripts to a single bundle', async ({ build, readFile }) => {
try {
await build();
} catch(err) {
} catch (err) {
console.error(err.stack);
assert.ok(!err);
return;