Compare commits

...

5 commits

Author SHA1 Message Date
bholmesdev
be4a8eaeb6 feat: only load CSS when mdx is rendered! 2022-10-20 17:47:43 -04:00
bholmesdev
92e641b849 revert: SSR asset flag babel changes 2022-10-20 17:46:07 -04:00
bholmesdev
4b1ad3c635 wip: exclude astro-ssr-asset styles from build 2022-10-19 15:00:39 -04:00
bholmesdev
ff93d376d3 wip: add ?astro-asset-ssr flag 2022-10-19 11:39:26 -04:00
bholmesdev
6c4ba5e8b5 fix: serialize route pattern for Netlify edge
Co-authored-by: Jackie Macharia <jackiewmacharia>
2022-10-19 10:12:56 -04:00
9 changed files with 95 additions and 6 deletions

View file

@ -6,6 +6,7 @@ import { resolvedPagesVirtualModuleId } from '../app/index.js';
export function* walkParentInfos(
id: string,
ctx: { getModuleInfo: GetModuleInfo },
until?: (importer: string) => boolean,
depth = 0,
seen = new Set<string>(),
childId = ''
@ -16,12 +17,13 @@ export function* walkParentInfos(
let order = childId ? info.importedIds.indexOf(childId) : 0;
yield [info, depth, order];
}
if (until?.(id)) return;
const importers = (info?.importers || []).concat(info?.dynamicImporters || []);
for (const imp of importers) {
if (seen.has(imp)) {
continue;
}
yield* walkParentInfos(imp, ctx, ++depth, seen, id);
yield* walkParentInfos(imp, ctx, until, ++depth, seen, id);
}
}

View file

@ -9,6 +9,7 @@ import { emptyDir, removeDir } from '../../core/fs/index.js';
import { prependForwardSlash } from '../../core/path.js';
import { isModeServerWithNoAdapter } from '../../core/util.js';
import { runHookBuildSetup } from '../../integrations/index.js';
import { assetSsrPlugin } from '../../vite-plugin-asset-ssr/index.js';
import { PAGE_SCRIPT_ID } from '../../vite-plugin-scripts/index.js';
import { info } from '../logger/core.js';
import { getOutDirWithinCwd } from './common.js';
@ -150,6 +151,7 @@ async function ssrBuild(opts: StaticBuildOptions, internals: BuildInternals, inp
target: 'server',
}),
...(viteConfig.plugins || []),
assetSsrPlugin({ internals }),
// SSR needs to be last
settings.config.output === 'server' && vitePluginSSR(internals, settings.adapter!),
vitePluginAnalyzer(internals),

View file

@ -19,6 +19,7 @@ export interface PageBuildData {
route: RouteData;
moduleSpecifier: string;
css: Map<string, { depth: number; order: number }>;
delayedCss?: Set<string>;
hoistedScript: { type: 'inline' | 'external'; value: string } | undefined;
}
export type AllPagesData = Record<ComponentPath, PageBuildData>;

View file

@ -15,6 +15,7 @@ import {
getPageDatasByHoistedScriptId,
isHoistedScript,
} from './internal.js';
import { DELAYED_ASSET_FLAG } from '../../vite-plugin-asset-ssr/index.js';
interface PluginOptions {
internals: BuildInternals;
@ -115,6 +116,7 @@ export function rollupPluginAstroBuildCSS(options: PluginOptions): VitePlugin[]
for (const [_, chunk] of Object.entries(bundle)) {
if (chunk.type === 'chunk') {
const c = chunk;
if ('viteMetadata' in chunk) {
const meta = chunk['viteMetadata'] as ViteMetadata;
@ -155,8 +157,31 @@ export function rollupPluginAstroBuildCSS(options: PluginOptions): VitePlugin[]
// For this CSS chunk, walk parents until you find a page. Add the CSS to that page.
for (const id of Object.keys(c.modules)) {
for (const [pageInfo, depth, order] of walkParentInfos(id, this)) {
if (moduleIsTopLevelPage(pageInfo)) {
for (const [pageInfo, depth, order] of walkParentInfos(
id,
this,
function until(importer) {
return importer.endsWith(DELAYED_ASSET_FLAG);
}
)) {
if (pageInfo.id.endsWith(DELAYED_ASSET_FLAG)) {
for (const parent of walkParentInfos(id, this)) {
console.log('walking parent...');
const parentInfo = parent[0];
if (moduleIsTopLevelPage(parentInfo)) {
const pageViteID = parentInfo.id;
const pageData = getPageDataByViteID(internals, pageViteID);
if (pageData) {
if (!pageData.delayedCss) {
pageData.delayedCss = new Set();
}
for (const css of meta.importedCss) {
pageData.delayedCss.add(css);
}
}
}
}
} else if (moduleIsTopLevelPage(pageInfo)) {
const pageViteID = pageInfo.id;
const pageData = getPageDataByViteID(internals, pageViteID);
if (pageData) {

View file

@ -20,6 +20,7 @@ import astroScriptsPlugin from '../vite-plugin-scripts/index.js';
import astroScriptsPageSSRPlugin from '../vite-plugin-scripts/page-ssr.js';
import { createCustomViteLogger } from './errors.js';
import { resolveDependency } from './util.js';
import { injectDelayedAssetPlugin } from '../vite-plugin-asset-ssr/index.js';
interface CreateViteOptions {
settings: AstroSettings;
@ -85,6 +86,7 @@ export async function createVite(
astroPostprocessVitePlugin({ settings }),
astroIntegrationsContainerPlugin({ settings, logging }),
astroScriptsPageSSRPlugin({ settings }),
injectDelayedAssetPlugin(),
],
publicDir: fileURLToPath(settings.config.publicDir),
root: fileURLToPath(settings.config.root),

View file

@ -0,0 +1,49 @@
import { Plugin } from 'vite';
import { moduleIsTopLevelPage, walkParentInfos } from '../core/build/graph.js';
import { BuildInternals, getPageDataByViteID } from '../core/build/internal.js';
const assetPlaceholder = `'@@ASTRO-ASSET-PLACEHOLDER@@'`;
export const DELAYED_ASSET_FLAG = '?astro-asset-ssr';
export function injectDelayedAssetPlugin(): Plugin {
return {
name: 'astro-inject-delayed-asset-plugin',
enforce: 'post',
load(id) {
if (id.endsWith(DELAYED_ASSET_FLAG)) {
const code = `
export { Content } from ${JSON.stringify(id.replace(DELAYED_ASSET_FLAG, ''))};
export const collectedCss = ${assetPlaceholder}
`;
return code;
}
},
};
}
export function assetSsrPlugin({ internals }: { internals: BuildInternals }): Plugin {
return {
name: 'astro-asset-ssr-plugin',
async generateBundle(_options, bundle) {
for (const [_, chunk] of Object.entries(bundle)) {
if (chunk.type === 'chunk' && chunk.code.includes(assetPlaceholder)) {
for (const id of Object.keys(chunk.modules)) {
for (const [pageInfo, depth, order] of walkParentInfos(id, this)) {
if (moduleIsTopLevelPage(pageInfo)) {
const pageViteID = pageInfo.id;
const pageData = getPageDataByViteID(internals, pageViteID);
if (pageData) {
chunk.code = chunk.code.replace(
assetPlaceholder,
JSON.stringify([...(pageData.delayedCss ?? [])])
);
}
}
}
}
}
}
},
};
}

View file

@ -185,7 +185,9 @@ export default function jsx({ settings, logging }: AstroPluginJSXOptions): Plugi
}
defaultJSXRendererEntry = [...jsxRenderersIntegrationOnly.entries()][0];
},
async transform(code, id, opts) {
async transform(code, unresolvedId, opts) {
let id = unresolvedId;
const ssr = Boolean(opts?.ssr);
if (!JSX_EXTENSIONS.has(path.extname(id))) {
return null;

View file

@ -86,7 +86,8 @@ export default function mdx(mdxOptions: MdxOptions = {}): AstroIntegration {
},
// Override transform to alter code before MDX compilation
// ex. inject layouts
async transform(_, id) {
async transform(_, unresolvedId) {
let id = unresolvedId;
if (!id.endsWith('mdx')) return;
// Read code from file manually to prevent Vite from parsing `import.meta.env` expressions
@ -112,7 +113,8 @@ export default function mdx(mdxOptions: MdxOptions = {}): AstroIntegration {
{
name: '@astrojs/mdx-postprocess',
// These transforms must happen *after* JSX runtime transformations
transform(code, id) {
transform(code, unresolvedId) {
let id = unresolvedId;
if (!id.endsWith('.mdx')) return;
// Ensures styles and scripts are injected into a `<head>`

View file

@ -57,6 +57,10 @@ async function createEdgeManifest(routes: RouteData[], entryFile: string, dir: U
path: route.pathname,
});
} else {
console.log({
og: route.pattern.source.toString(),
new: route.pattern.source.replace(/\\\//g, '/').toString(),
});
functions.push({
function: entryFile,
// Make route pattern serializable to match expected