Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add the output option #4015

Merged
merged 22 commits into from
Jul 25, 2022
Merged
Show file tree
Hide file tree
Changes from 12 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
36 changes: 36 additions & 0 deletions .changeset/famous-coins-destroy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
---
'astro': minor
'@astrojs/cloudflare': minor
'@astrojs/deno': minor
'@astrojs/image': minor
'@astrojs/netlify': minor
'@astrojs/node': minor
'@astrojs/sitemap': minor
'@astrojs/vercel': minor
---

New `mode` configuration option
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changeset needs to be updated to refer to output


This change introduces a new configuration option `mode`. Mode can be either

* `static` - The default, when building a static site.
* `server` - When building an app to be deployed for SSR (server-side rendering).

The default, `static`, can be omitted from your config file.

If you want to use SSR you now need to provide `mode: 'server'` *in addition* to an adapter.

The `adapter` configuration has been renamed to `deploy`. In the future adapters will support configuring a static site as well!

For SSR make this change:

```diff
import { defineConfig } from 'astro/config';
import netlify from '@astrojs/netlify/functions';

export default defineConfig({
- adapter: netlify(),
+ deploy: netlify(),
+ mode: 'server',
});
```
5 changes: 5 additions & 0 deletions .changeset/lucky-apes-yell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
matthewp marked this conversation as resolved.
Show resolved Hide resolved
---

Update "astro add" output to remove confusing multi-select prompt.
5 changes: 5 additions & 0 deletions .changeset/perfect-drinks-fold.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Update the help output to improve formatting
3 changes: 2 additions & 1 deletion examples/ssr/astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import node from '@astrojs/node';

// https://astro.build/config
export default defineConfig({
adapter: node(),
mode: 'server',
deploy: node(),
integrations: [svelte()],
});
1 change: 1 addition & 0 deletions packages/astro/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"./package.json": "./package.json",
"./runtime/*": "./dist/runtime/*",
"./server/*": "./dist/runtime/server/*",
"./adapter-node/server.js": "./dist/adapter-node/server.js",
"./vite-plugin-astro": "./dist/vite-plugin-astro/index.js",
"./vite-plugin-astro/*": "./dist/vite-plugin-astro/*",
"./vite-plugin-astro-postprocess": "./dist/vite-plugin-astro-postprocess/index.js",
Expand Down
13 changes: 8 additions & 5 deletions packages/astro/src/@types/astro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@ export interface BuildConfig {
client: URL;
server: URL;
serverEntry: string;
staticMode: boolean | undefined;
}

/**
Expand Down Expand Up @@ -622,7 +621,7 @@ export interface AstroUserConfig {
/**
* @docs
* @kind heading
* @name Adapter
* @name Deploy
* @description
*
* Deploy to your favorite server, serverless, or edge host with build adapters. Import one of our first-party adapters for [Netlify](https://docs.astro.build/en/guides/deploy/netlify/#adapter-for-ssredge), [Vercel](https://docs.astro.build/en/guides/deploy/vercel/#adapter-for-ssr), and more to engage Astro SSR.
Expand All @@ -633,11 +632,15 @@ export interface AstroUserConfig {
* import netlify from '@astrojs/netlify/functions';
* {
* // Example: Build for Netlify serverless deployment
* adapter: netlify(),
* deploy: netlify(),
* }
* ```
*/
adapter?: AstroIntegration;
deploy?: AstroIntegration;

// TODO: Document
matthewp marked this conversation as resolved.
Show resolved Hide resolved
mode?: 'static' | 'server';


/**
* @docs
Expand Down Expand Up @@ -750,7 +753,7 @@ export interface AstroConfig extends z.output<typeof AstroConfigSchema> {
// This is a more detailed type than zod validation gives us.
// TypeScript still confirms zod validation matches this type.
integrations: AstroIntegration[];
adapter?: AstroIntegration;

// Private:
// We have a need to pass context based on configured state,
// that is different from the user-exposed configuration.
Expand Down
23 changes: 0 additions & 23 deletions packages/astro/src/adapter-ssg/index.ts

This file was deleted.

4 changes: 2 additions & 2 deletions packages/astro/src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ async function runCommand(cmd: string, flags: yargs.Arguments) {
}
}

let { astroConfig, userConfig, userConfigPath } = await openConfig({ cwd: root, flags, cmd });
let { astroConfig, userConfig, userConfigPath } = await openConfig({ cwd: root, flags, cmd, logging });
telemetry.record(event.eventCliSession(cmd, userConfig, flags));

// Common CLI Commands:
Expand All @@ -154,7 +154,7 @@ async function runCommand(cmd: string, flags: yargs.Arguments) {
watcher.on('add', async function restartServerOnNewConfigFile(addedFile: string) {
// if there was not a config before, attempt to resolve
if (!userConfigPath && addedFile.includes('astro.config')) {
const addedConfig = await openConfig({ cwd: root, flags, cmd });
const addedConfig = await openConfig({ cwd: root, flags, cmd, logging });
if (addedConfig.userConfigPath) {
info(logging, 'astro', 'Astro config detected. Restarting server...');
astroConfig = addedConfig.astroConfig;
Expand Down
14 changes: 9 additions & 5 deletions packages/astro/src/core/add/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,15 +66,21 @@ export default async function add(names: string[], { cwd, flags, logging, teleme
['--yes', 'Accept all prompts.'],
['--help', 'Show this help message.'],
],
'Example: Add a UI Framework': [
'Recommended: UI Frameworks': [
['react', 'astro add react'],
['preact', 'astro add preact'],
['vue', 'astro add vue'],
['svelte', 'astro add svelte'],
['solid-js', 'astro add solid-js'],
['lit', 'astro add lit'],
],
'Example: Add an Integration': [
'Recommended: Hosting': [
['netlify', 'astro add netlify'],
['vercel', 'astro add vercel'],
['cloudflare', 'astro add cloudflare'],
['deno', 'astro add deno'],
],
'Recommended: Integrations': [
['tailwind', 'astro add tailwind'],
['partytown', 'astro add partytown'],
['sitemap', 'astro add sitemap'],
Expand All @@ -85,9 +91,7 @@ export default async function add(names: string[], { cwd, flags, logging, teleme
['deno', 'astro add deno'],
],
},
description: `Check out the full integration catalog: ${cyan(
'https://astro.build/integrations'
)}`,
description: `For more integrations, check out: ${cyan('https://astro.build/integrations')}`,
});
return;
}
Expand Down
6 changes: 3 additions & 3 deletions packages/astro/src/core/build/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import { debug, info } from '../logger/core.js';
import { render } from '../render/core.js';
import { createLinkStylesheetElementSet, createModuleScriptsSet } from '../render/ssr-element.js';
import { createRequest } from '../request.js';
import { getOutputFilename, isBuildingToSSR } from '../util.js';
import { getOutputFilename } from '../util.js';
import { getOutFile, getOutFolder } from './common.js';
import { eachPageData, getPageDataByComponent } from './internal.js';
import type { PageBuildData, SingleFileBuiltModule, StaticBuildOptions } from './types';
Expand Down Expand Up @@ -97,7 +97,7 @@ export async function generatePages(
const timer = performance.now();
info(opts.logging, null, `\n${bgGreen(black(' generating static routes '))}`);

const ssr = isBuildingToSSR(opts.astroConfig);
const ssr = opts.astroConfig.mode === 'server';
const serverEntry = opts.buildConfig.serverEntry;
const outFolder = ssr ? opts.buildConfig.server : opts.astroConfig.outDir;
const ssrEntryURL = new URL('./' + serverEntry + `?time=${Date.now()}`, outFolder);
Expand Down Expand Up @@ -207,7 +207,7 @@ async function generatePath(
}
}

const ssr = isBuildingToSSR(opts.astroConfig);
const ssr = opts.astroConfig.mode === 'server';
const url = new URL(opts.astroConfig.base + removeLeadingForwardSlash(pathname), origin);
const options: RenderOptions = {
adapterName: undefined,
Expand Down
17 changes: 9 additions & 8 deletions packages/astro/src/core/build/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { AstroTelemetry } from '@astrojs/telemetry';
import type { AstroConfig, BuildConfig, ManifestData, RuntimeMode } from '../../@types/astro';
import type { AstroAdapter, AstroConfig, BuildConfig, ManifestData, RuntimeMode } from '../../@types/astro';
import type { LogOptions } from '../logger/core';

import fs from 'fs';
Expand All @@ -18,7 +18,7 @@ import { debug, info, levels, timerMessage } from '../logger/core.js';
import { apply as applyPolyfill } from '../polyfill.js';
import { RouteCache } from '../render/route-cache.js';
import { createRouteManifest } from '../routing/index.js';
import { createSafeError, isBuildingToSSR } from '../util.js';
import { createSafeError } from '../util.js';
import { collectPagesData } from './page-data.js';
import { staticBuild } from './static-build.js';
import { getTimeStat } from './util.js';
Expand Down Expand Up @@ -98,11 +98,13 @@ class AstroBuilder {
client: new URL('./client/', this.config.outDir),
server: new URL('./server/', this.config.outDir),
serverEntry: 'entry.mjs',
staticMode: undefined,
};
await runHookBuildStart({ config: this.config, buildConfig });

info(this.logging, 'build', 'Collecting build information...');
const getPrettyDeployTarget = (adapter: AstroAdapter | undefined) => adapter?.name || 'unknown';
info(this.logging, 'build', `build target: ${colors.green(this.config.mode)}`);
info(this.logging, 'build', `deploy target: ${colors.green(getPrettyDeployTarget(this.config._ctx.adapter))}`);
info(this.logging, 'build', 'Collecting build info...');
this.timer.loadStart = performance.now();
const { assets, allPages } = await collectPagesData({
astroConfig: this.config,
Expand All @@ -111,7 +113,7 @@ class AstroBuilder {
origin,
routeCache: this.routeCache,
viteServer,
ssr: isBuildingToSSR(this.config),
ssr: this.config.mode === 'server',
});

debug('build', timerMessage('All pages loaded', this.timer.loadStart));
Expand Down Expand Up @@ -168,12 +170,11 @@ class AstroBuilder {
});

if (this.logging.level && levels[this.logging.level] <= levels['info']) {
const buildMode = isBuildingToSSR(this.config) ? 'ssr' : 'static';
await this.printStats({
logging: this.logging,
timeStart: this.timer.init,
pageCount: pageNames.length,
buildMode,
buildMode: this.config.mode,
});
}
}
Expand All @@ -198,7 +199,7 @@ class AstroBuilder {
logging: LogOptions;
timeStart: number;
pageCount: number;
buildMode: 'static' | 'ssr';
buildMode: 'static' | 'server';
}) {
const total = getTimeStat(timeStart, performance.now());

Expand Down
6 changes: 1 addition & 5 deletions packages/astro/src/core/build/page-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import { debug } from '../logger/core.js';
import { removeTrailingForwardSlash } from '../path.js';
import { callGetStaticPaths, RouteCache, RouteCacheEntry } from '../render/route-cache.js';
import { matchRoute } from '../routing/match.js';
import { isBuildingToSSR } from '../util.js';

export interface CollectPagesDataOptions {
astroConfig: AstroConfig;
Expand All @@ -36,9 +35,6 @@ export async function collectPagesData(
const assets: Record<string, string> = {};
const allPages: AllPagesData = {};
const builtPaths = new Set<string>();

const buildMode = isBuildingToSSR(astroConfig) ? 'ssr' : 'static';
matthewp marked this conversation as resolved.
Show resolved Hide resolved

const dataCollectionLogTimeout = setInterval(() => {
info(opts.logging, 'build', 'The data collection step may take longer for larger projects...');
clearInterval(dataCollectionLogTimeout);
Expand Down Expand Up @@ -72,7 +68,7 @@ export async function collectPagesData(
};

clearInterval(routeCollectionLogTimeout);
if (buildMode === 'static') {
if (astroConfig.mode === 'static') {
const html = `${route.pathname}`.replace(/\/?$/, '/index.html');
debug(
'build',
Expand Down
27 changes: 17 additions & 10 deletions packages/astro/src/core/build/static-build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,11 @@ import { fileURLToPath } from 'url';
import * as vite from 'vite';
import { BuildInternals, createBuildInternals } from '../../core/build/internal.js';
import { prependForwardSlash } from '../../core/path.js';
import { emptyDir, removeDir } from '../../core/util.js';
import { emptyDir, removeDir, isModeServerWithNoAdapter } from '../../core/util.js';
import { runHookBuildSetup } from '../../integrations/index.js';
import { rollupPluginAstroBuildCSS } from '../../vite-plugin-build-css/index.js';
import type { ViteConfigWithSSR } from '../create-vite';
import { info } from '../logger/core.js';
import { isBuildingToSSR } from '../util.js';
import { generatePages } from './generate.js';
import { trackPageData } from './internal.js';
import type { PageBuildData, StaticBuildOptions } from './types';
Expand All @@ -25,6 +24,16 @@ import { injectManifest, vitePluginSSR } from './vite-plugin-ssr.js';
export async function staticBuild(opts: StaticBuildOptions) {
const { allPages, astroConfig } = opts;

// Verify this app is buildable.
if(isModeServerWithNoAdapter(opts.astroConfig)) {
throw new Error(`Cannot use mode: 'server' without an adapter. Please install and configure an adapter by setting it on the deploy configuration.

export default {
mode: 'static',
adapter: netlify(),
}`)
}

// The pages to be built for rendering purposes.
const pageInput = new Set<string>();

Expand Down Expand Up @@ -60,9 +69,7 @@ export async function staticBuild(opts: StaticBuildOptions) {
info(
opts.logging,
'build',
isBuildingToSSR(astroConfig)
? 'Building SSR entrypoints...'
: 'Building entrypoints for prerendering...'
`Building ${astroConfig.mode} entrypoints...`
);
const ssrResult = (await ssrBuild(opts, internals, pageInput)) as RollupOutput;
info(opts.logging, 'build', dim(`Completed in ${getTimeStat(timer.ssr, performance.now())}.`));
Expand All @@ -83,7 +90,7 @@ export async function staticBuild(opts: StaticBuildOptions) {
await clientBuild(opts, internals, clientInput);

timer.generate = performance.now();
if (opts.buildConfig.staticMode) {
if (astroConfig.mode === 'static') {
try {
await generatePages(ssrResult, opts, internals, facadeIdToPageDataMap);
} finally {
Expand All @@ -100,7 +107,7 @@ export async function staticBuild(opts: StaticBuildOptions) {

async function ssrBuild(opts: StaticBuildOptions, internals: BuildInternals, input: Set<string>) {
const { astroConfig, viteConfig } = opts;
const ssr = isBuildingToSSR(astroConfig);
const ssr = astroConfig.mode === 'server';
const out = ssr ? opts.buildConfig.server : astroConfig.outDir;

const viteBuildConfig: ViteConfigWithSSR = {
Expand Down Expand Up @@ -144,7 +151,7 @@ async function ssrBuild(opts: StaticBuildOptions, internals: BuildInternals, inp
}),
...(viteConfig.plugins || []),
// SSR needs to be last
isBuildingToSSR(opts.astroConfig) && vitePluginSSR(internals, opts.astroConfig._ctx.adapter!),
opts.astroConfig.mode === 'server' && vitePluginSSR(internals, opts.astroConfig._ctx.adapter!),
vitePluginAnalyzer(opts.astroConfig, internals),
],
publicDir: ssr ? false : viteConfig.publicDir,
Expand Down Expand Up @@ -174,7 +181,7 @@ async function clientBuild(
) {
const { astroConfig, viteConfig } = opts;
const timer = performance.now();
const ssr = isBuildingToSSR(astroConfig);
const ssr = astroConfig.mode === 'server';
const out = ssr ? opts.buildConfig.client : astroConfig.outDir;

// Nothing to do if there is no client-side JS.
Expand Down Expand Up @@ -275,7 +282,7 @@ async function copyFiles(fromFolder: URL, toFolder: URL) {

async function ssrMoveAssets(opts: StaticBuildOptions) {
info(opts.logging, 'build', 'Rearranging server assets...');
const serverRoot = opts.buildConfig.staticMode
const serverRoot = opts.astroConfig.mode === 'static'
? opts.buildConfig.client
: opts.buildConfig.server;
const clientRoot = opts.buildConfig.client;
Expand Down
Loading