From 1bab90653976d767ecc96756309a08f9732fecee Mon Sep 17 00:00:00 2001 From: Matthew Phillips Date: Fri, 11 Jun 2021 09:03:22 -0400 Subject: [PATCH] Remove second snowpack instance (#368) * Remove second snowpack instance * Document import.meta.env.SSR * Remove unnecessary Promise.all --- .changeset/rare-nails-sneeze.md | 5 ++ docs/api.md | 18 +++++ .../src/components/PluginSearchPage.jsx | 2 +- packages/astro/src/build.ts | 2 +- packages/astro/src/runtime.ts | 65 ++++++------------- packages/astro/src/snowpack-logger.ts | 18 ----- .../astro-fallback/src/components/Client.jsx | 2 +- 7 files changed, 45 insertions(+), 67 deletions(-) create mode 100644 .changeset/rare-nails-sneeze.md diff --git a/.changeset/rare-nails-sneeze.md b/.changeset/rare-nails-sneeze.md new file mode 100644 index 000000000..757f50926 --- /dev/null +++ b/.changeset/rare-nails-sneeze.md @@ -0,0 +1,5 @@ +--- +'astro': minor +--- + +Removes a second instance of snowpack which degraded peformance diff --git a/docs/api.md b/docs/api.md index 9037b75de..ed04ab5a8 100644 --- a/docs/api.md +++ b/docs/api.md @@ -146,6 +146,24 @@ Astro will generate an RSS 2.0 feed at `/feed/[collection].xml` (for example, `/ ``` +### `import.meta` + +All ESM modules include a `import.meta` property. Astro adds `import.meta.env` through [Snowpack](https://www.snowpack.dev/). + +__import.meta.env.SSR__ can be used to know when rendering on the server. Some times you might want different logic, for example a component that should only be rendered in the client: + +```jsx +import { h } from 'preact'; + +export default function() { + return ( + import.meta.env.SSR ? +
: + + ) +} +``` + [canonical]: https://en.wikipedia.org/wiki/Canonical_link_element [config]: ../README.md#%EF%B8%8F-configuration [docs-collections]: ./collections.md diff --git a/examples/snowpack/src/components/PluginSearchPage.jsx b/examples/snowpack/src/components/PluginSearchPage.jsx index 4ed46cb74..4bf9a0f82 100644 --- a/examples/snowpack/src/components/PluginSearchPage.jsx +++ b/examples/snowpack/src/components/PluginSearchPage.jsx @@ -117,7 +117,7 @@ function PluginSearchPageLive() { } export default function PluginSearchPage(props) { - return import.meta.env.astro ? ( + return import.meta.env.SSR ? (
Loading...
) : ( diff --git a/packages/astro/src/build.ts b/packages/astro/src/build.ts index 484b9dbec..ef26c5a5c 100644 --- a/packages/astro/src/build.ts +++ b/packages/astro/src/build.ts @@ -58,7 +58,7 @@ export async function build(astroConfig: AstroConfig, logging: LogOptions = defa const mode: RuntimeMode = 'production'; const runtime = await createRuntime(astroConfig, { mode, logging: runtimeLogging }); const { runtimeConfig } = runtime; - const { backendSnowpack: snowpack } = runtimeConfig; + const { snowpack } = runtimeConfig; try { // 0. erase build directory diff --git a/packages/astro/src/runtime.ts b/packages/astro/src/runtime.ts index 8a9ff1548..9eeab014b 100644 --- a/packages/astro/src/runtime.ts +++ b/packages/astro/src/runtime.ts @@ -20,12 +20,9 @@ interface RuntimeConfig { astroConfig: AstroConfig; logging: LogOptions; mode: RuntimeMode; - backendSnowpack: SnowpackDevServer; - backendSnowpackRuntime: SnowpackServerRuntime; - backendSnowpackConfig: SnowpackConfig; - frontendSnowpack: SnowpackDevServer; - frontendSnowpackRuntime: SnowpackServerRuntime; - frontendSnowpackConfig: SnowpackConfig; + snowpack: SnowpackDevServer; + snowpackRuntime: SnowpackServerRuntime; + snowpackConfig: SnowpackConfig; } // info needed for collection generation @@ -50,7 +47,7 @@ configureSnowpackLogger(snowpackLogger); /** Pass a URL to Astro to resolve and build */ async function load(config: RuntimeConfig, rawPathname: string | undefined): Promise { - const { logging, backendSnowpackRuntime, frontendSnowpack } = config; + const { logging, snowpackRuntime, snowpack } = config; const { pages: pagesRoot, buildOptions, devOptions } = config.astroConfig; let origin = buildOptions.site ? new URL(buildOptions.site).origin : `http://localhost:${devOptions.port}`; @@ -62,7 +59,7 @@ async function load(config: RuntimeConfig, rawPathname: string | undefined): Pro const searchResult = searchForPage(fullurl, pagesRoot); if (searchResult.statusCode === 404) { try { - const result = await frontendSnowpack.loadUrl(reqPath); + const result = await snowpack.loadUrl(reqPath); if (!result) throw new Error(`Unable to load ${reqPath}`); // success return { @@ -88,7 +85,7 @@ async function load(config: RuntimeConfig, rawPathname: string | undefined): Pro let rss: { data: any[] & CollectionRSS } = {} as any; try { - const mod = await backendSnowpackRuntime.importModule(snowpackURL); + const mod = await snowpackRuntime.importModule(snowpackURL); debug(logging, 'resolve', `${reqPath} -> ${snowpackURL}`); // handle collection @@ -297,10 +294,8 @@ interface RuntimeOptions { } interface CreateSnowpackOptions { - env: Record; mode: RuntimeMode; resolvePackageUrl?: (pkgName: string) => Promise; - target: 'frontend' | 'backend'; } const DEFAULT_HMR_PORT = 12321; @@ -309,11 +304,11 @@ const DEFAULT_RENDERERS = ['@astrojs/renderer-vue', '@astrojs/renderer-svelte', /** Create a new Snowpack instance to power Astro */ async function createSnowpack(astroConfig: AstroConfig, options: CreateSnowpackOptions) { const { projectRoot, pages: pagesRoot, renderers = DEFAULT_RENDERERS } = astroConfig; - const { env, mode, resolvePackageUrl, target } = options; + const { mode, resolvePackageUrl } = options; const frontendPath = new URL('./frontend/', import.meta.url); const resolveDependency = (dep: string) => resolve.sync(dep, { basedir: fileURLToPath(projectRoot) }); - const isHmrEnabled = mode === 'development' && target === 'backend'; + const isHmrEnabled = mode === 'development'; let snowpack: SnowpackDevServer; let astroPluginOptions: { @@ -419,9 +414,6 @@ async function createSnowpack(astroConfig: AstroConfig, options: CreateSnowpackO }, }); - const envConfig = snowpackConfig.env || (snowpackConfig.env = {}); - Object.assign(envConfig, env); - snowpack = await startSnowpackServer( { config: snowpackConfig, @@ -438,53 +430,34 @@ async function createSnowpack(astroConfig: AstroConfig, options: CreateSnowpackO /** Core Astro runtime */ export async function createRuntime(astroConfig: AstroConfig, { mode, logging }: RuntimeOptions): Promise { + let snowpack: SnowpackDevServer; const timer: Record = {}; - const resolvePackageUrl = async (pkgName: string) => frontendSnowpack.getUrlForPackage(pkgName); + const resolvePackageUrl = async (pkgName: string) => snowpack.getUrlForPackage(pkgName); timer.backend = performance.now(); const { - snowpack: backendSnowpack, - snowpackRuntime: backendSnowpackRuntime, - snowpackConfig: backendSnowpackConfig, + snowpack: snowpackInstance, + snowpackRuntime, + snowpackConfig, } = await createSnowpack(astroConfig, { - target: 'backend', - env: { - astro: true, - }, mode, resolvePackageUrl, }); - debug(logging, 'core', `backend snowpack created [${stopTimer(timer.backend)}]`); - - timer.frontend = performance.now(); - const { - snowpack: frontendSnowpack, - snowpackRuntime: frontendSnowpackRuntime, - snowpackConfig: frontendSnowpackConfig, - } = await createSnowpack(astroConfig, { - target: 'frontend', - env: { - astro: false, - }, - mode, - }); - debug(logging, 'core', `frontend snowpack created [${stopTimer(timer.frontend)}]`); + snowpack = snowpackInstance; + debug(logging, 'core', `snowpack created [${stopTimer(timer.backend)}]`); const runtimeConfig: RuntimeConfig = { astroConfig, logging, mode, - backendSnowpack, - backendSnowpackRuntime, - backendSnowpackConfig, - frontendSnowpack, - frontendSnowpackRuntime, - frontendSnowpackConfig, + snowpack, + snowpackRuntime, + snowpackConfig, }; return { runtimeConfig, load: load.bind(null, runtimeConfig), - shutdown: () => Promise.all([backendSnowpack.shutdown(), frontendSnowpack.shutdown()]).then(() => void 0), + shutdown: () => snowpack.shutdown(), }; } diff --git a/packages/astro/src/snowpack-logger.ts b/packages/astro/src/snowpack-logger.ts index abb2248ba..4898faa6a 100644 --- a/packages/astro/src/snowpack-logger.ts +++ b/packages/astro/src/snowpack-logger.ts @@ -1,8 +1,6 @@ import { logger as snowpackLogger } from 'snowpack'; import { defaultLogLevel } from './logger.js'; -const onceMessages = ['Ready!', 'watching for file changes'].map((str) => new RegExp(`\\[snowpack\\](.*?)${str}`)); - const neverWarn = new RegExp( '(' + /(run "snowpack init" to create a project config file.)|/.source + @@ -26,20 +24,4 @@ export function configureSnowpackLogger(logger: typeof snowpackLogger) { } console.error(message); }); - - logger.on('info', (message) => { - // Cache messages that should only be shown once. - // This is due to having 2 snowpack instances. Once that is removed we can - // get rid of this workaround. - if (messageCache.has(message)) { - return; - } - - const shouldBeCached = onceMessages.some((exp) => exp.test(message)); - if (shouldBeCached) { - messageCache.add(message); - } - - console.log(message); - }); } diff --git a/packages/astro/test/fixtures/astro-fallback/src/components/Client.jsx b/packages/astro/test/fixtures/astro-fallback/src/components/Client.jsx index 4cc5ea252..28e72df14 100644 --- a/packages/astro/test/fixtures/astro-fallback/src/components/Client.jsx +++ b/packages/astro/test/fixtures/astro-fallback/src/components/Client.jsx @@ -1,5 +1,5 @@ import { h } from 'preact'; export default function (props) { - return
{import.meta.env.astro ? 'static' : 'dynamic'}
; + return
{import.meta.env.SSR ? 'static' : 'dynamic'}
; }