diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index c96b3b27c..fb4c1afd5 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -1,47 +1,5 @@ # docs -## 0.0.6 - -### Patch Changes - -- 788c769d: # Hoisted scripts - - This change adds support for hoisted scripts, allowing you to bundle scripts together for a page and hoist them to the top (in the head): - - ```astro - - ``` - -## 0.0.5 - -## 0.0.5-next.0 - -### Patch Changes - -- 78b5bde1: Adds support for Astro.resolve - - `Astro.resolve()` helps with creating URLs relative to the current Astro file, allowing you to reference files within your `src/` folder. - - Astro _does not_ resolve relative links within HTML, such as images: - - ```html - - ``` - - The above will be sent to the browser as-is and the browser will resolve it relative to the current **page**. If you want it to be resolved relative to the .astro file you are working in, use `Astro.resolve`: - - ```astro - - ``` - -## 0.0.4 - -### Patch Changes - -- adc767c5: change Spanish translations for Getting Started page - ## 0.0.3 ### Patch Changes diff --git a/docs/README.md b/docs/README.md index 623b6ede3..5fd357fad 100644 --- a/docs/README.md +++ b/docs/README.md @@ -11,7 +11,7 @@ Every pull request needs to be reviewed by another contributor to the documentat - Clone/Fork the project - This project uses yarn to manage dependencies. [Make sure that you have yarn v1 installed.](https://classic.yarnpkg.com/) - Run `yarn install` to install latest dependencies. -- Run `yarn dev` to start the dev server. +- Run `yarn start` to start the dev server. - Run `yarn build` to build the final site for production. The environment variable `SNOWPACK_PUBLIC_GITHUB_TOKEN` must be set to a personal access token with `public_repo` permissions to prevent rate-limiting. diff --git a/docs/package.json b/docs/package.json index 2e76c3009..9c9540636 100644 --- a/docs/package.json +++ b/docs/package.json @@ -1,23 +1,21 @@ { "name": "docs", - "version": "0.0.6", + "version": "0.0.3", "private": true, "scripts": { - "dev": "astro dev", "start": "astro dev", "build": "astro build", - "preview": "astro preview", "lint": "run-p --aggregate-output lint:linkcheck", - "lint:a11y": "start-test 'yarn dev --silent' 3000 'yarn lint:a11y:local'", + "lint:a11y": "start-test 'yarn start --silent' 3000 'yarn lint:a11y:local'", "lint:a11y:local": "pa11y-ci --sitemap 'http://localhost:3000/sitemap.xml' --sitemap-find 'https://docs.astro.build' --sitemap-replace 'http://localhost:3000'", "lint:a11y:remote": "pa11y-ci --sitemap 'https://docs.astro.build/sitemap.xml'", - "lint:linkcheck": "start-test 'yarn dev --silent' 3000 'yarn lint:linkcheck:local'", + "lint:linkcheck": "start-test 'yarn start --silent' 3000 'yarn lint:linkcheck:local'", "lint:linkcheck:local": "blc -ro --user-agent 'broken-link-checker/0.7.8' 'http://localhost:3000'", "lint:linkcheck:remote": "blc -ro --user-agent 'broken-link-checker/0.7.8' 'https://docs.astro.build/'" }, "devDependencies": { "@snowpack/plugin-dotenv": "^2.1.0", - "astro": "^0.20.2", + "astro": "^0.20.4", "broken-link-checker": "^0.7.8", "npm-run-all": "^4.1.5", "pa11y-ci": "^2.4.2", diff --git a/docs/public/code.css b/docs/public/code.css index 0543b8416..3fbb26626 100644 --- a/docs/public/code.css +++ b/docs/public/code.css @@ -4,11 +4,6 @@ color: #fd9170; } -.language-diff .token.prefix.deleted, -.language-diff .token.prefix.inserted { - user-select: none; -} - [class*='language-'] .namespace { opacity: 0.7; } diff --git a/docs/public/index.css b/docs/public/index.css index ba7fce412..abd3b5e98 100644 --- a/docs/public/index.css +++ b/docs/public/index.css @@ -36,7 +36,7 @@ nav ul { } .content > section > * + * { - margin-top: 1.25rem; + margin-top: 1rem; } .content > section > :first-child { @@ -44,19 +44,13 @@ nav ul { } /* Typography */ -h1, -h2, -h3, -h4, -h5, -h6 { +:is(h1, h2, h3, h4, h5, h6) { margin-bottom: 1rem; font-weight: bold; line-height: 1; } -h1, -h2 { +:is(h1, h2) { max-width: 40ch; } @@ -64,34 +58,39 @@ h2 { margin-top: 3rem; } -:is(h4, h5, h6):not(:first-child) { - margin-top: 2rem; -} - h1 { - font-size: 3.25rem; - font-weight: 800; + font-size: 2.25rem; } h2 { - font-size: 2.5rem; + font-size: 1.5rem; } h3 { - font-size: 1.75rem; + font-size: 1.125rem; } h4 { - font-size: 1.3rem; -} - -h5 { font-size: 1rem; } -p, -.content ul { - line-height: 1.65em; +h5 { + font-size: 0.8rem; +} + +@media (min-width: 50em) { + h1 { + font-size: 3.25rem; + font-weight: 800; + } + + h2 { + font-size: 2rem; + } + + h3 { + font-size: 1.25rem; + } } p, @@ -106,13 +105,14 @@ small, a { color: var(--theme-text-accent); + font-weight: 400; text-underline-offset: 0.08em; align-items: center; gap: 0.5rem; } article > section :is(ul, ol) > * + * { - margin-top: 0.25rem; + margin-top: 0.75rem; } article > section nav :is(ul, ol) > * + * { diff --git a/docs/public/theme.css b/docs/public/theme.css index 551ee15e0..1eec0a709 100644 --- a/docs/public/theme.css +++ b/docs/public/theme.css @@ -94,7 +94,6 @@ body { --theme-divider: hsla(var(--color-gray-10), 1); --theme-text: hsla(var(--color-gray-90), 1); --theme-text-light: hsla(var(--color-gray-80), 1); - /* @@@: not used anywhere */ --theme-text-lighter: hsla(var(--color-gray-40), 1); --theme-bg: hsla(215, 28%, 17%, 1); @@ -107,17 +106,6 @@ body { --theme-navbar-bg: hsla(215, 28%, 17%, 1); --theme-selection-color: hsla(var(--color-base-white), 100%, 1); --theme-selection-bg: hsla(var(--color-purple), var(--theme-accent-opacity)); - - /* DocSearch [Algolia] */ - --docsearch-modal-background: var(--theme-bg); - --docsearch-searchbox-focus-background: var(--theme-divider); - --docsearch-footer-background: var(--theme-divider); - --docsearch-text-color: var(--theme-text); - --docsearch-hit-background: var(--theme-divider); - --docsearch-hit-shadow: none; - --docsearch-hit-color: var(--theme-text); - --docsearch-footer-shadow: inset 0 2px 10px #000; - --docsearch-modal-shadow: inset 0 0 8px #000; } ::selection { diff --git a/docs/reference/api-reference.md b/docs/reference/api-reference.md index 3f3d8526b..08580bcf1 100644 --- a/docs/reference/api-reference.md +++ b/docs/reference/api-reference.md @@ -42,7 +42,7 @@ const data = Astro.fetchContent('../pages/post/*.md'); // returns an array of po **/ astro: { headers: [], // an array of h1...h6 elements in the markdown file - source: '', // raw source of the markdown file + source: '' // raw source of the markdown file html: '' // rendered HTML of the markdown file }, url: '' // the rendered path @@ -171,7 +171,7 @@ Astro will generate an RSS 2.0 feed at `/feed/[collection].xml` (for example, `/ 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. Sometimes you might want different logic, for example a component that should only be rendered in the client: +**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'; diff --git a/docs/src/components/HeadCommon.astro b/docs/src/components/HeadCommon.astro index 9687c32a5..46fe72743 100644 --- a/docs/src/components/HeadCommon.astro +++ b/docs/src/components/HeadCommon.astro @@ -1,8 +1,6 @@ - - @@ -30,10 +28,10 @@ - + + gtag('config', 'G-TEL60V1WM9'); + \ No newline at end of file diff --git a/docs/src/components/HeadSEO.astro b/docs/src/components/HeadSEO.astro index be6b016c7..5553eb2d0 100644 --- a/docs/src/components/HeadSEO.astro +++ b/docs/src/components/HeadSEO.astro @@ -5,10 +5,8 @@ export interface Props { site: any, canonicalURL: URL | string, }; -const { - content = {}, - canonicalURL, - } = Astro.props; +const { content = {}, canonicalURL } = Astro.props; +const formattedContentTitle = content.title ? `${content.title} 🚀 ${SITE.title}` : SITE.title; const imageSrc = content?.image?.src ?? OPEN_GRAPH.image.src; const canonicalImageSrc = new URL(imageSrc, Astro.site); const imageAlt = content?.image?.alt ?? OPEN_GRAPH.image.alt; @@ -17,7 +15,7 @@ const imageAlt = content?.image?.alt ?? OPEN_GRAPH.image.alt; - + @@ -29,7 +27,7 @@ const imageAlt = content?.image?.alt ?? OPEN_GRAPH.image.alt; - + diff --git a/docs/src/components/Header/Header.astro b/docs/src/components/Header/Header.astro index 968ba69b2..8471e4ebf 100644 --- a/docs/src/components/Header/Header.astro +++ b/docs/src/components/Header/Header.astro @@ -23,7 +23,6 @@ const lang = currentPage && getLanguageFromURL(currentPage); .logo { - direction: ltr; display: flex; overflow: hidden; width: 30px; diff --git a/docs/src/components/Header/LanguageSelect.css b/docs/src/components/Header/LanguageSelect.css index 5411e50dc..b95ef5048 100644 --- a/docs/src/components/Header/LanguageSelect.css +++ b/docs/src/components/Header/LanguageSelect.css @@ -3,13 +3,13 @@ width: 48px; box-sizing: border-box; margin: 0; - padding: 0.33em 2rem; + padding: 0.33em 0.5em; overflow: visible; font-weight: 500; font-size: 1rem; font-family: inherit; line-height: inherit; - background-color: var(--theme-bg); + background-color: transparent; border-color: var(--theme-text-lighter); color: var(--theme-text-light); border-style: solid; @@ -21,7 +21,8 @@ transition-duration: 0.2s; transition-property: border-color, color; -webkit-font-smoothing: antialiased; - -webkit-appearance: none; + padding-left: 30px; + padding-right: 1rem; } .language-select-wrapper .language-select:hover, .language-select-wrapper .language-select:focus { @@ -34,37 +35,13 @@ } .language-select-wrapper > svg { position: absolute; - top: 8px; - left: 8px; - pointer-events: none; -} - -.language-select-wrapper::before, -.language-select-wrapper::after { - position: absolute; - top: 18px; - content: ''; - width: 8px; - height: 1px; - background: var(--theme-text-light); -} -.language-select-wrapper::before { - right: 10px; - transform: rotate(45deg); -} -.language-select-wrapper::after { - right: 5px; - transform: rotate(-45deg); + top: 7px; + left: 10px; + z-index: -1; } @media (min-width: 50em) { .language-select { width: 100%; } - .language-select-wrapper::before { - right: 16px; - } - .language-select-wrapper::after { - right: 11px; - } } diff --git a/docs/src/components/Header/LanguageSelect.tsx b/docs/src/components/Header/LanguageSelect.tsx index 6385afdd3..46e3dd0f3 100644 --- a/docs/src/components/Header/LanguageSelect.tsx +++ b/docs/src/components/Header/LanguageSelect.tsx @@ -68,25 +68,7 @@ const LanguageSelect: FunctionalComponent<{ lang: string }> = ({ lang }) => { 简体中文 - - - - - - diff --git a/docs/src/components/Header/Search.css b/docs/src/components/Header/Search.css index 563f67bc5..b11a59290 100644 --- a/docs/src/components/Header/Search.css +++ b/docs/src/components/Header/Search.css @@ -3,17 +3,6 @@ --docsearch-primary-color: var(--theme-accent); --docsearch-logo-color: var(--theme-text); } - -.DocSearch-Modal .DocSearch-Hit a { - box-shadow: none; - border: 1px solid var(--theme-accent); -} - -/** Style Search Bar */ -.search-placeholder { - flex-grow: 1; - text-align: initial; -} .search-input { flex-grow: 1; box-sizing: border-box; @@ -51,6 +40,9 @@ color: var(--theme-text-light); } .search-hint { + position: absolute; + top: 7px; + right: 19px; padding: 3px 5px; display: none; display: none; diff --git a/docs/src/components/Header/Search.tsx b/docs/src/components/Header/Search.tsx index 5f05f744f..a1684e49f 100644 --- a/docs/src/components/Header/Search.tsx +++ b/docs/src/components/Header/Search.tsx @@ -51,7 +51,7 @@ export default function Search() { strokeLinejoin="round" /> - Search + Search Press / diff --git a/docs/src/components/LeftSidebar/LeftSidebar.astro b/docs/src/components/LeftSidebar/LeftSidebar.astro index 1960dbb04..a065797cc 100644 --- a/docs/src/components/LeftSidebar/LeftSidebar.astro +++ b/docs/src/components/LeftSidebar/LeftSidebar.astro @@ -1,11 +1,9 @@ --- import { SIDEBAR } from '../../config.ts'; -import { getLanguageFromURL, removeLeadingSlash, removeTrailingSlash } from '../../util.ts'; +import { getLanguageFromURL } from '../../util.ts'; const {currentPage} = Astro.props; - -// Get the slug w/o a leading or trailing slash -const currentPageMatch = removeLeadingSlash(removeTrailingSlash(currentPage)); -const langCode = getLanguageFromURL(currentPage); +const currentPageMatch = currentPage.slice(1); +const langCode = 'en'; // getLanguageFromURL(currentPage); // SIDEBAR is a flat array. Group it by sections to properly render. const sidebarSections = SIDEBAR[langCode].reduce((col, item) => { if (item.header) { diff --git a/docs/src/components/PageContent/PageContent.astro b/docs/src/components/PageContent/PageContent.astro index 564b8485b..fd1e9d242 100644 --- a/docs/src/components/PageContent/PageContent.astro +++ b/docs/src/components/PageContent/PageContent.astro @@ -1,17 +1,9 @@ --- -const {content, githubEditUrl, currentPage} = Astro.props; +const {content, githubEditUrl} = Astro.props; const title = content.title; const headers = content.astro.headers; import MoreMenu from '../RightSidebar/MoreMenu.astro'; import TableOfContents from '../RightSidebar/TableOfContents.tsx'; -import {getLanguageFromURL} from '../../util.ts'; -import {SIDEBAR} from '../../config.ts'; -const langCode = getLanguageFromURL(currentPage); -const links = SIDEBAR[langCode].filter(x => x.link && typeof x.header === 'undefined'); -// handle cases with a trailing slash or not -const index = links.findIndex(x => `/${x.link}/` === currentPage || `/${x.link}` === currentPage); -const next = index !== -1 ? (index === links.length - 1 ? null : links[index + 1]) : null; -const previous = index !== -1 ? (index === 0 ? null : links[index - 1]) : null; --- - - -``` - -Vous venez de lire un exemple de syntaxe des composants Astro, inspirée par le HTML et le JSX. - -Vous pouvez continuer à ajouter des fichiers dans le dossier `src/pages`, et Astro se servira du nom du fichier pour ajouter des pages à votre site. Par exemple, si vous ajoutez une page `src/pages/a-propos.astro` (par exemple en reprenant le code ci-dessus), Astro va générer une nouvelle page à l'adresse `http://localhost:3000/a-propos`. - -## [Démarrer Astro](#démarrer-astro) - -```bash -npm run dev -``` - -Astro va démarrer votre site à l'adresse `http://localhost:3000`. En ouvrant cette URL dans votre navigateur, vous devriez voir s'afficher "Hello, World", ou bien la page créée précédemment. - -## [Compiler avec Astro](#compiler-avec-astro) - -```bash -npm run build -``` - -Astro va produire une version allégée du site et la sauvegarder directement sur le disque. Votre application se trouvera dans le dossier `dist/`. - -## Prochaines étapes - -Vous êtes désormais prêt·e à développer ! - -Nous vous recommandons de prendre le temps de vous familiariser avec Astro et son fonctionnement. Nous vous recommandons les guides suivants : - -📚 En savoir plus sur [la structure des projets Astro](/core-concepts/project-structure). - -📚 En savoir plus sur [la syntaxe des composants Astro](/core-concepts/astro-components). - -📚 En savoir plus sur [la génération des adresses à partir de l'arborescence.](/core-concepts/astro-pages). diff --git a/docs/src/pages/fr/quick-start.md b/docs/src/pages/fr/quick-start.md deleted file mode 100644 index 6cb5a2b3e..000000000 --- a/docs/src/pages/fr/quick-start.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -layout: ~/layouts/MainLayout.astro -title: Démarrage rapide -lang: fr ---- - -```shell -# Prérequis : vérifiez que Node.js est en version 12.20.0+, 14.13.1+, ou 16+ -node --version - -# Créez un nouveau dossier, et placez-vous dedans -mkdir my-astro-project && cd $_ - -# Attention au décollage... -npm init astro - -# Installez les dépendances -npm install - -# Commencez à coder ! -npm run dev - -# Quand votre site est fin prêt, compilez-en une version statique dans le dossier `dist/` -npm run build -``` - -Si vous désirez en savoir plus sur les différentes façons d'installer Astro dans votre projet, [lisez notre guide d'installation](installation). - -## Commencez votre projet - -Depuis un terminal ouvert dans votre projet, entrez la commande suivante : - -```bash -npm run dev -``` - -Astro va lancer un serveur local sur [http://localhost:3000](http://localhost:3000). Ouvrez cette adresse dans votre navigateur, et vous devriez voir le "Hello, World" d'Astro. - -Vous n'avez jamais besoin de redémarrer Astro : à chaque modification dans le dossier `src/`, le serveur recompile votre site. - -## Compilez votre projet - -Pour compiler votre projet, entrez la commande suivante dans un terminal : - -```bash -npm run build -``` - -Astro va produire une version allégée de votre site et la sauvegarder directement sur le disque. Votre application se trouvera dans le dossier `dist/`. - -## Mettez en production - -Les sites compilés avec Astros sont statiques, et peuvent par conséquent être déployés par votre hébergeur préféré : - -- [Vercel](https://vercel.com/) -- [Netlify](https://www.netlify.com/) -- [S3 bucket](https://aws.amazon.com/s3/) -- [Google Firebase](https://firebase.google.com/) -- [Lire le guide de déploiement sur la documentation Astro](/guides/deploy) - -## Prochaines étapes - -Vous êtes désormais prêt·e à développer ! - -Nous vous recommandons de prendre le temps de vous familiariser avec Astro et son fonctionnement. Nous vous recommandons les guides suivants : - -📚 En savoir plus sur [la structure des projets Astro](/core-concepts/project-structure). - -📚 En savoir plus sur [la syntaxe des composants Astro](/core-concepts/astro-components). - -📚 En savoir plus sur [la génération des adresses à partir de l'arborescence.](/core-concepts/astro-pages). diff --git a/docs/src/pages/404.astro b/docs/src/pages/group-1/404.astro similarity index 71% rename from docs/src/pages/404.astro rename to docs/src/pages/group-1/404.astro index 242cbf594..c8e249d23 100644 --- a/docs/src/pages/404.astro +++ b/docs/src/pages/group-1/404.astro @@ -1,5 +1,5 @@ --- -import SplashLayout from '../layouts/SplashLayout.astro'; +import SplashLayout from '../../layouts/SplashLayout.astro'; --- diff --git a/docs/src/pages/group-1/blog/island-architecture.md b/docs/src/pages/group-1/blog/island-architecture.md new file mode 100644 index 000000000..78be15c92 --- /dev/null +++ b/docs/src/pages/group-1/blog/island-architecture.md @@ -0,0 +1,241 @@ +--- +layout: ~/layouts/MainLayout.astro +title: Island Architecture +draft: true +--- + + + + + +> "No man is an island. However, Web Components should be" + +The concept behind Island architecture comes from [Jason Miller](https://twitter.com/_developit), The creator of [Preact](https://preactjs.com/) and a Google, DevRel Engineer. + +In the summer of 2020, he managed to formulated his thoughts of how web architecture should be, in the idyllic sense, and placed them onto his [blog post](https://jasonformat.com/islands-architecture/). + +His seminal post outlines and discusses the general concept of 'islands' as an architectural design process that could be used in Web Development, allowing for better improvements in overall site performance, SEO, UX, and everywhere else. His given explanation describing this new paradigm, was extraordinarily succinct: + +> "The general idea of an _"Islands"_ architecture is deceptively simple: Render HTML pages on the server, and inject placeholders or slots around highly dynamic regions. These placeholders/slots contain the server-rendered HTML output from their corresponding widget. They denote regions that can then be "hydrated" on the client into small self-contained widgets, reusing their server-rendered initial HTML."-Jason Miller + +To develop a better understanding of what Jason meant with his proposal, let's quickly explore the backdrop, before we explain 'Island Architecture' and how it is applied into Astro as our primary ethos. + +## Programming Paradigms + +Think of a simple webpage. On which are many different types of components that are shown on this page, components that are shared across the site, others contain fixed content, some are a bit more elaborate that may perhaps use different state's or need to fetch multiple data streams from external sources. + +Such a site would have very few actual 'moving' pieces, or _dynamic_ elements. For the most part the content tends to be fixed, and static. + +In order to allow for dynamism and interactivity we are often left making overly complex solutions to deliver the slightest form of action on the application. + +Complexity becomes inherent in the design process of the application. As a result, developers have to adopt some dogma, that comes from certain architectural design styles and patterns. + +Given the [catalogue of patterns](https://en.wikipedia.org/wiki/List_of_software_architecture_styles_and_patterns) that are available, utilizing the right architecture for the application often comes from hard-to-obtain experience. + +Web developers tend to gravitate towards tried and tested practices, and none fit the requirements better than the [Model-View-Controller](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) (**MVC**) design pattern. + +Where the **Model** contains the data structures and logic that governs the use of the data in the application. **Views** are the visual representation of the data that the user sees, and the **Controller** connects the views to their relevant data _Models_ based on their interactions with the User. + +This design pattern works well for our [client-server](https://en.wikipedia.org/wiki/Client%E2%80%93server_model) based applications. Since the models are placed on the _servers_, the views that are sent back over the wire tend to be static _documents_, controllers are sent along with the static files to facilitate the behaviours that web developers created for their application, in the form of _scripts_. + +## Rise of the Frameworks + +A vast swathe of libraries, frameworks and tooling rose up to meet the challenges of providing a Developer Experience (DX) that would let them create their applications, _'freely'_. + +Helping to abstract away much of the complexity needed in implementing architectural design decisions into their application. + +The likes of; [ASP.NET](https://dotnet.microsoft.com/learn/aspnet/what-is-aspnet-core) and [Blazor](https://dotnet.microsoft.com/apps/aspnet/web-apps/blazor) for [.NET](https://dotnet.microsoft.com/), [Ruby On Rails](https://rubyonrails.org/), [Laravel](https://laravel.com/) & [Symphony](https://symfony.com/) for [PHP](https://www.php.net/), are examples of the MVC patterns seen in other server-side programming languages. + +For a long time, JavaScript was solely restricted to the Browser, then [Node.js](https://nodejs.org/en/) appeared. Node.js is a standalone JavaScript runtime built on the Chrome V8 engine. + +This was a seismic shift that occurred in Web Development, by allowing JavaScript to escape the browser and operate on the server, developers could use JS on both; Front & Back-ends, when developing their applications. + +Within the new JavaScript + Node ecosystem, JS MVC frameworks began to appear, e.g: [BackboneJS](https://backbonejs.org/), [ExpressJS](https://expressjs.com/), [Ember](https://emberjs.com/), [MeteorJS](https://www.meteor.com/), to name but a few. + +This pattern of statically generated content on the server was becoming a bit of a performance bottleneck. + +Where some asset-heavy page would take longer to render on the server than a lighter page. + +This would block subsequent requests being made to the server, and more crucially responses being sent back from the server. + +Server performance and optimisation only addressed the problem so far, but with larger payloads and pages being sent more frequently, something had to be done. + +Frameworks, rose again to the challenge of delivering a better User Experience (UX) began to ship [Single Page Applications](https://en.wikipedia.org/wiki/Single-page_application) (**SPA**) to the client. + +SPA's became a fast and effective ways to sending feature-rich applications to the client without the load being placed on the server. + +Instead rendering the application would now be carried out wholly on the client device. Thus allowing the Server to send a single, simple, page to the client. + +There are many benefits in providing a SPA to Clients. SPA's never needs a page refresh, since all the files (HTML/CSS/JS) had already been sent over the wire. + +This only required the End-User's web browser to then read and render the application to the screen. + +But SPA's came with their own hidden cost that comes with abstracting away the complexity. Recognising the many issues with SPA's from a holistic DX to a seamless UX/UI. + +Frameworks began to appear in the ecosystem that allowed developers to build even more advanced Single-Page-Applications. + +Some of these were developed by industry leaders, such as Google with their [Angular Project](https://angularjs.org/), [React](https://reactjs.org/) which was open sourced by Facebook. Or by the JS community themselves driving changes with [Preact](https://preactjs.com/), [Vue](https://vuejs.org/) and [Svelte](https://svelte.dev/), [Webpack](https://webpack.js.org/) & [Babel](https://babeljs.io/setup) + +## The Status Quo + +It's slightly hubris to suggest that the web development ecosystem had at all settled for any period of time, well at least long enough for a Status Quo to coalesce. + +However, given the vibrancy and versatility of the ecosystem, a status quo had indeed began to take hold. + +Rooted in the deepest annals of the developers psyche, was the slow conformity towards embracing UI frameworks to build the whole site as applications instead of the dynamic components that it was meant for. + +Everything ended up being sent to the Client. From Rendering to Routing, bundled payload sizes drastically increased, and client devices were asked to do a lot more. + +By placing the onus on the client, Server stress was indeed lessened. But there was a cost to this status quo. + +The End-User experience was drastically suffering, for their devices now became the bottleneck, unable to execute the massive payloads that were being sent back from the server. + +As demonstrated, JavaScript and its community are quick to change in certain places and slow in others. The gradual adoption of [EcmaScript Modules](https://tc39.es/ecma262/#sec-modules)(**ESM**) as a standard to the JavaScript spec was a complete sea-change to the ecosystem. + +Prior to the formalisation of ESM, module usage in JS were often limited to libraries and were difficult to use outside the browser. + +Using community developed conventions, helped push the goal of a modular ecosystem with [CommonJS](https://en.wikipedia.org/wiki/CommonJS)(**CJS**). + +Node v12 shipped with ESM Modules as part of the standard in node. Signalling the start of something entirely new. + +## The Great Migration + +ESM adoption was indeed slow, the gradual migration from `require()` to `import()` took a while. + +Now developing in an ESM world, allows for certain advantages to be exploited. + +This wanting exploitation of new features have given way for another influx of new libraries, frameworks, tooling and a whole suite of new methods of writing JS. + +We are now experiencing new tools in the ecosystem that feature ESM as defaults. + +By doing so we can take full advantage of unbundled developer environments, allowing for projects to start-up in the tens of milliseconds, instead of whole seconds and full minutes. + +Using ESM in the Browser, tools can build once and cache forever. Tree-shaking and code optimisations can occur, more frequently and with greater efficacy. Reducing massive bundle sizes down to a few hundred Kilobytes. + +Tools like [Snowpack](https://www.snowpack.dev/) and [Vite](https://vitejs.dev/) introduce a whole new experience that developers were previously denied in their development process and that is speed. + +With cut-edge DX features like [HMR](https://npm.io/package/esm-hmr) has quickly became the industry de facto, and build times reduced by a factor of 100x. + +This new generation of ESM tools is extremely encouraging for web developers. + +## A Brave New World + +Into this new age ESM world, we have had a dearth of innovation from the established frameworks to address some of the root issues that plagued web development over its time. + +Basic questions of : Websites or WebApp's were still unresolved. Where to render the site, on the server or on the client, perhaps a bit of both? What determines the need for dynamic content and what specifies content to be static? + +Witnessing frameworks slowly go full circle and return to Server-Side-Rendering (_SSR_) their applications was in part only allowed to be considered in an ESM world, however it was a bit of an admission of culpability of sorts. + +By inadvertently admitting that the current model is flawed, opened up the space for a new form of discourse to enter, and help redefine the ecosystem moving forward. + +SSR frameworks such as [Next.js](https://nextjs.org/), [Nuxt.js](https://nuxtjs.org/), [SvelteKit](https://kit.svelte.dev/), did help address some of the underling questions, within the current paradigm. + +Developing methods and techniques to deliver production-stable SSR along with tooling and support for the developer. + +But in a new age, retaining previously disputed tenants only aided the lack of innovation in this new dawn. + +Jason Miller's formulations of an 'Island'-styled approach only augments the discussion with fresh new ideas about Website and Application development. + +## The Golden Isles and its many Islands + +In the introduction we placed a quote from Jason, describing the general concept of Island architecture. Let's revisit his words, since we have a better understanding of the context in which this is being proposed. + +Jason asks us to think of a Island architecture as a static HTML document. One that is rendered entirely on the server. + +The document contains multiple separate embedded applications, that are injected into placeholders or '_slots_', which form dynamic regions on the page. + +The Server renders HTML outputs form each of these dynamic components, and places them onto the static document being sent back down to the End-User. + +These slots, of dynamic regions, can then be '_hydrated_'. [Hydration]() is a process that allows for Client-Sided JS to convert and make static HTML, dynamic, reusing their initial server-rendered HTML. + +This 'micro' architecture is similar to both 'micro-frontends' and 'micro-services'. Both share the concept of breaking applications into small indivisible units. But the problem is that a lot of the small modular units are rarely composed in HTML. + +With Island-Architecture, he proposes a form of progressive enhancement for the dynamic components by using a technique known as _Partial Hydration_. + +Let's look at the following analogy: + +On our Static page, we have an image carousel. Such carousel needs to have some form of interactivity to load the next image after a certain amount of time has elapsed, along with navigation and pagination buttons on the carousel. + +To do this we would need to implement some behaviour on our carousel. + +In the traditional sense, we might be using a React Component to help create the aforementioned experience. In order to do this we would have to include the React-runtime plugin as a top-level ` -``` - -Or it can link to an external JavaScript file: - -```astro - -``` - -A hoisted script can be within a page or a component, and no matter how many times the component is used, the script will only be added once: - -```astro ---- -import TwitterTimeline from '../components/TwitterTimeline.astro'; ---- - -<-- The script will only be injected into the head once. --> - - - -``` - ## Comparing `.astro` versus `.jsx` `.astro` files can end up looking very similar to `.jsx` files, but there are a few key differences. Here's a comparison between the two formats. @@ -347,7 +312,7 @@ Since `src/pages/about.astro` will build to `/about/index.html`, you may not hav ``` -The recommended approach is to place files within `public/*`. This references a file at `public/thumbnail.png`, which will resolve to `/thumbnail.png` at the final build (since `public/` ends up at `/`). +The recommended approach is to place files within `public/*`. This references a file it `public/thumbnail.png`, which will resolve to `/thumbnail.png` at the final build (since `public/` ends up at `/`). #### Option 2: Asset import references diff --git a/docs/src/pages/core-concepts/astro-pages.md b/docs/src/pages/group-1/core-concepts/astro-pages.md similarity index 100% rename from docs/src/pages/core-concepts/astro-pages.md rename to docs/src/pages/group-1/core-concepts/astro-pages.md diff --git a/docs/src/pages/group-1/core-concepts/collections.md b/docs/src/pages/group-1/core-concepts/collections.md new file mode 100644 index 000000000..ef209e8a4 --- /dev/null +++ b/docs/src/pages/group-1/core-concepts/collections.md @@ -0,0 +1,292 @@ +--- +layout: ~/layouts/MainLayout.astro +title: Collections +--- + +**Collections** are a special type of [page](/core-concepts/astro-pages) in Astro that can generate multiple pages at different URLs for a larger set of data. If you've seen an Astro file that starts with a dollar sign (ex: `$posts.astro`), that's a collection. + +Example use-cases include: + +- Generating multiple pages from remote data +- Generating multiple pages from local data (ex: list all markdown posts) +- pagination: `/posts/1`, `/posts/2`, etc. +- Grouping items into multiple pages: `/author/fred`, `/author/matthew`, etc. +- Generating one page per item: `/pokemon/pikachu`, `/pokemon/charmander`, etc. + +**Use a Collection when you need to generate multiple pages from a single template.** If you just want to generate a single page -- like a long list linking to every post on your blog -- then you can just use a normal [page](/core-concepts/astro-pages). + +## Using Collections + +To create a new Astro Collection, you need to do two things: + +### 1. Create the File + +Create a new file in the `src/pages` directory that starts with the dollar sign (`$`) symbol. This symbol is required to enable the Collections API. + +Astro uses file-based routing, which means that the file must match the URL that you expect to generate. You are able to define a custom route structure in the next step, but the collection file name must always match the start of the URL. + +- **Example**: `src/pages/$tags.astro` -> `/tags/:tag` +- **Example**: `src/pages/$posts.astro` -> `/posts/1`, `/posts/2`, etc. + +### 2. Export createCollection + +Every collection must define and export a `createCollection` function inside the component script. This exported function is where you fetch your data for the entire collection and tell Astro the exact URLs that you'd like to generate. It **MUST** be named `createCollection` and it must be exported. Check out the examples below for examples of how this should be implemented. + +```astro +--- +export async function createCollection() { + /* fetch collection data here */ + return { /* see examples below */ }; +} +--- + +``` + +API Reference: [createCollection](/reference/api-reference#collections-api) + +## Example: Individual Pages + +One of the most common reasons to use a collection is to generate a page for every item fetched from a larger dataset. In this example, we'll query a remote API and use the result to generate 150 different pages: one for each pokemon returned by the API call. + +Run this example in development, and then visit [http://localhost:3000/pokemon/pikachu](http://localhost:3000/pokemon/pikachu) to see one of the generated pages. + +```jsx +--- +// Example: src/pages/$pokemon.astro +// Define a `createCollection` function. +// In this example, we'll create a new page for every single pokemon. +export async function createCollection() { + // Do your data fetching here. + const allPokemonResponse = await fetch(`https://pokeapi.co/api/v2/pokemon?limit=150`); + const allPokemonResult = await allPokemonResponse.json(); + const allPokemon = allPokemonResult.results; + return { + // `route` defines the URL structure for your collection. + // You can use any URL path pattern here, as long as it + // matches the filename prefix (`$pokemon.astro` -> `/pokemon/*`). + route: `/pokemon/:name`, + // `paths` tells Astro which pages to generate in your collection. + // Provide an array of `params` objects that match the `route` pattern. + paths() { + return allPokemon.map((pokemon, i) => ({params: {name: pokemon.name}})); + }, + // For each individual page, return the data needed on each page. + // If you needed to fetch more data for each page, you can do that here as well. + // Luckily, we loaded all of the data that we need at the top of the function. + async props({ params }) { + return {item: allPokemon.find((pokemon) => pokemon.name === params.name)}; + }, + }; +} +// The rest of your component script now runs on each individual page. +// "item" is one of the props returned in the `props()` function. +const {item} = Astro.props; +--- + + + Pokemon: {item.name}</head> + <body> + Who's that pokemon? It's {item.name}! + </body> +</html> +``` + +## Example: Grouping Content by Page + +You can also group items by page. In this example, we'll fetch data from the same Pokemon API. But instead of generating 150 pages, we'll just generate one page for every letter of the alphabet, creating an alphabetical index of Pokemon. + +_Note: Looking for pagination? Collections have built-in support to make pagination easy. Be sure to check out the next example._ + +```jsx +--- +// Define a `createCollection` function. +export async function createCollection() { + // Do your data fetching here. + const allPokemonResponse = await fetch(`https://pokeapi.co/api/v2/pokemon?limit=150`); + const allPokemonResult = await allPokemonResponse.json(); + const allPokemon = allPokemonResult.results; + const allLetters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']; + return { + // `route` defines the URL structure for your collection. + // You can use any URL path pattern here, as long as it + // matches the filename prefix (`$pokemon.astro` -> `/pokemon/*`). + route: `/pokemon/:letter`, + // `paths` tells Astro which pages to generate in your collection. + // Provide an array of `params` objects that match the `route` pattern. + // Here, we create a route for each letter (ex: "a" -> {letter: "a"}). + paths() { + return allLetters.map(letter => ({params: {letter}})); + }, + // `props` returns the data needed on each page. + // For each individual page, return the data needed on each page. + // If you needed to fetch more data for each page, you can do that here as well. + // Luckily, we loaded all of the data that we need at the top of the function. + async props({ params }) { + return { + letter: params.letter, + items: allPokemon.filter((pokemon) => pokemon.name[0] === params.letter)}; + }, + }; +} +// The rest of your component script now runs on each individual page. +// "item" is one of the props returned in the `props()` function. +const {letter, items} = Astro.props; +--- +<html lang="en"> + <head> + <title>Page: {letter}</head> + <body> + {items.map((pokemon) => (<h1>{pokemon.name}</h1>))} + </body> +</html> +``` + +## Example: Pagination + +Pagination is a common use-case for static websites. Astro has built-in pagination support that was designed to make pagination effortless. Just pass `paginate: true` in the `createCollection` return object to enable automatic pagination. + +This example provides a basic implementation of pagination. In the previous examples, we had fetched from a remote API. In this example, we'll fetch our local markdown files to create a paginated list of all posts for a blog. + +```jsx +--- +// Define a `createCollection` function. +export async function createCollection() { + const allPosts = Astro.fetchContent('../posts/*.md') // fetch local posts... + .sort((a, b) => a.title.localeCompare(b.title)); // ... and sort by title. + + return { + // Set "paginate" to true to enable pagination. + paginate: true, + // Remember to add the ":page?" param for pagination. + // The "?" indicates an optional param, since the first page does not use it. + // Example: `/posts`, `/posts/2`, `/posts/3`, etc. + route: '/posts/:page?', + // `paths()` - not needed if `:page?` is your only route param. + // If you define have other params in your route, then you will still + // need a paths() function similar to the examples above. + // + // `props()` - notice the new `{paginate}` argument! This is passed to + // the props() function when `paginate` is set to true. We can now use + // it to enable pagination on a certain prop. In this example, we paginate + // "posts" so that multiple pages will be generated based on the given page size. + async props({paginate}) { + return { + posts: paginate(allPosts, {pageSize: 10}), + }; + }, + }; +} +// Now, you can get the paginated posts from your props. +// Note that a paginated prop is a custom object format, where the data +// for the page is available at `posts.data`. See the next example to +// learn how to use the other properties of this object. +const {posts} = Astro.props; +--- +<html lang="en"> + <head> + <title>Pagination Example + + + {posts.data.map((post) => ( +

{post.title}

+ + Read Post + ))} + + +``` + +## Example: Pagination Metadata + +Building on the example above: when you use the `paginate` API you get access to several other properties in the paginated data prop. Your paginated prop includes important metadata +for the collection, such as: `.page` for keeping track of your page number and `.url` for linking to other pages in the collection. + +In this example, we'll use these values to add pagination UI controls to your HTML template. + +```jsx +--- +export async function createCollection() { /* See Previous Example */ } +// Remember that a paginated prop uses a custom object format to help with pagination. +const {posts} = Astro.props; +--- + + + Pagination Example: Page Number {posts.page.current} + + + + + +
+
Results {posts.start + 1}–{posts.end + 1} of {posts.total}
+
+
+

Page {posts.page.current} / {posts.page.last}

+ +
+ + +``` + +## RSS Feeds + +You can generate an RSS 2.0 feed from the `createCollection()` result by adding the `rss` option. Here are all the options: + +```jsx +export async function createCollection() { + return { + paginate: true, + route: '/posts/:page?', + async props({ paginate }) { + /* Not shown: see examples above */ + }, + rss: { + title: 'My RSS Feed', + // if you want a full text feed, add your markup here (e.g. item.astro.html) + description: 'Description of the feed', + // (optional) add xmlns:* properties to root element + xmlns: { + itunes: 'http://www.itunes.com/dtds/podcast-1.0.dtd', + content: 'http://purl.org/rss/1.0/modules/content/', + }, + // (optional) add arbitrary XML to + customData: `en-us +The Sunset Explorers`, + // Format each paginated item in the collection + item: (item) => ({ + title: item.title, + description: item.description, + // enforce GMT timezone (otherwise it'll be different based on where it's built) + pubDate: item.pubDate + 'Z', + // link is required, shows up in RSS readers + link: '/collection/' + item.id + // (optional) custom data is supported here as well + customData: ``${Astro.site}collection/${item.id}`` + }), + }, + }; +} +``` + +Astro will generate your RSS feed at the URL `/feed/[collection].xml`. For example, `/src/pages/$podcast.astro` would generate URL `/feed/podcast.xml`. + +Even though Astro will create the RSS feed for you, you'll still need to add `` tags manually in your `` HTML for feed readers and browsers to pick up: + +```html + +``` + +### 📚 Further Reading + +- [Fetching data in Astro](/guides/data-fetching) +- API Reference: [createCollection()](/reference/api-reference#createcollection) +- API Reference: [createCollection() > Pagination](/reference/api-reference#pagination) +- API Reference: [createCollection() > RSS](/reference/api-reference#rss) diff --git a/docs/src/pages/core-concepts/component-hydration.md b/docs/src/pages/group-1/core-concepts/component-hydration.md similarity index 82% rename from docs/src/pages/core-concepts/component-hydration.md rename to docs/src/pages/group-1/core-concepts/component-hydration.md index bb0fbce29..ed2ab453d 100644 --- a/docs/src/pages/core-concepts/component-hydration.md +++ b/docs/src/pages/group-1/core-concepts/component-hydration.md @@ -53,7 +53,7 @@ Besides the obvious performance benefits of sending less JavaScript down to the ## Hydrate Interactive Components -Astro renders every component on the server **at build time**, unless [client:only](#mycomponent-clientonly-) is used. To hydrate components on the client **at runtime**, you may use any of the following `client:*` directives. A directive is a component attribute (always with a `:`) which tells Astro how your component should be rendered. +Astro renders every component on the server **at build time**. To hydrate components on the client **at runtime**, you may use any of the following `client:*` directives. A directive is a component attribute (always with a `:`) which tells Astro how your component should be rendered. ```astro --- @@ -81,12 +81,6 @@ Hydrate the component as soon as the element enters the viewport (uses [Intersec Hydrate the component as soon as the browser matches the given media query (uses [matchMedia][mdn-mm]). Useful for sidebar toggles, or other elements that should only display on mobile or desktop devices. -### `` - -Hydrates the component at page load, similar to `client:load`. The component will be **skipped** at build time, useful for components that are entirely dependent on client-side APIs. This is best avoided unless absolutely needed, in most cases it is best to render placeholder content on the server and delay any browser API calls until the component hydrates in the browser. - -If more than one renderer is included in the Astro [config](/reference/configuration-reference), `client:only` needs a hint to know which renderer to use for the component. For example, `client:only="react"` would make sure that the component is hydrated in the browser with the React renderer. For custom renderers not provided by `@astrojs`, use the full name of the renderer provided in your Astro config, i.e. ``. - ## Can I Hydrate Astro Components? [Astro components](./astro-components) (`.astro` files) are HTML-only templating components with no client-side runtime. If you try to hydrate an Astro component with a `client:` modifier, you will get an error. diff --git a/docs/src/pages/core-concepts/layouts.md b/docs/src/pages/group-1/core-concepts/layouts.md similarity index 100% rename from docs/src/pages/core-concepts/layouts.md rename to docs/src/pages/group-1/core-concepts/layouts.md diff --git a/docs/src/pages/core-concepts/project-structure.md b/docs/src/pages/group-1/core-concepts/project-structure.md similarity index 100% rename from docs/src/pages/core-concepts/project-structure.md rename to docs/src/pages/group-1/core-concepts/project-structure.md diff --git a/docs/src/pages/group-1/de/getting-started.md b/docs/src/pages/group-1/de/getting-started.md new file mode 100644 index 000000000..f953d50ca --- /dev/null +++ b/docs/src/pages/group-1/de/getting-started.md @@ -0,0 +1,69 @@ +--- +layout: ~/layouts/MainLayout.astro +title: Einführung +lang: de +--- + +Astro ist ein moderner Generator für Statische Webseiten (SSG). Um mehr über Astro zu erfahren, schau dir [unsere Homepage](https://astro.build/) an und lies [unseren Release Blogpost](https://astro.build/blog/introducing-astro). + +Diese Seite dient als Übersicht der Astro Dokumentation und alle damit verbundenen Ressourcen. + +Du willst erstmal einen kurzen Überblick, um zu verstehen, was Astro ist? [Besuch unsere Homepage.](https://astro.build) + +## Astro ausprobieren + +Der einfachste Weg, Astro auszuprobieren ist `npm init astro` in einem neuen Verzeichnis deiner Wahl auszuführen. Der CLI wizard hilft dir dann dabei, ein neues Astro Projekt aufzusetzen. + +Um mit Astro in 5 einfachen Schritten loszulegen, lies [unsere Schnellstart Anleitung](/quick-start) + +Alternativ kannst du unsere [Installations Anleitung](/installation) für eine ausführliche Beschreibung des Installationsprozesses lesen. + +### Online Spielplätze + +Falls du lieber erstmal mit Astro in deinem Browser herumspielen willst, kannst du einen online Code Spielplatz benutzen. Probier unsere "Hello World" Vorlage auf [CodeSandbox](https://codesandbox.io/s/astro-template-hugb3). + +_Hinweis: Einige Funktionen (z.B. Fast Refresh) funktionieren aktuell nur begrenzt auf CodeSandbox._ + +## Astro lernen + +Es kommen eine Menge verschiedener Menschen mit unterschiedlichen Hintergründen und nochmal anderen Lernweisen zu Astro. Unabhängig davon, ob du lieber theoretisch oder praktisch lernst, hoffen wir, dass dir dieser Abschnitt hilfreich ist. + +- Falls du lieber **praktisch lernst**, such dir ein Beispiel aus unserer [Beispiel Liste](https://github.com/snowpackjs/astro/tree/main/examples) aus und fang direkt an. + +- Falls du lieber **theoretisch lernst**, kannst du mit unseren [grundlegenden Konzepten und Anleitungen](/core-concepts/project-structure) anfangen. + +Wie alle unbekannten Technologien, hat auch Astro einen leichte Lernkurve. Mit ein bisschen Übung und Geduld, sind wir aber _sicher_, dass du schnell lernst, wie du mit Astro umgehen kannst. + +### Lerne die `.astro` Syntax + +When du mit Astro anfängst, wirst du schnell Dateien mit der `.astro` Dateiendung finden. Das ist die **Astro Komponenten Syntax**: ein spezielles, HTML-ähnliches Dateiformat, welches Astro für Vorlagen benutzt. Es wurde angelehnt an HTML und JSX entworfen und sollte jedem, der damit Erfahrung hat, direkt bekannt vorkommen. + +Unsere Anleitung zu [Astro Komponenten](/core-concepts/astro-components) sollte eine gute Einführung in die Astro Syntax sein und ist der beste Weg, um diese zu lernen. + +### API Dokumentation + +Dieser Dokumentationsabschnitt sollte für dich nützlich sein, wenn du mehr Details über eine bestimme Astro API erfahren möchtest. + +So listet z.B. die [Konfigurations Dokumentation](/reference/configuration-reference) alle möglichen Konfigurationseigenschaften auf, die dir zur Verfügung stehen. In der [Dokumentation über eingebaute Komponenten](/reference/builtin-components) findest du alle verfügbaren Kernkomponenten wie `` und ``. + +### Versionierte Dokumentation + +Diese Dokumentation ist immer auf dem Stand der letzte _stable_ Version von Astro. Sobald wir den v1.0 Meilenstein erreicht haben, wollen wir versionierte Dokumentation einführen. + +## Bleib auf dem Laufenden + +Unser [@astrodotbuild](https://twitter.com/astrodotbuild) Twitter Account ist die offizielle Quelle für Neuigkeiten vom Astro Team. + +Zusätzlich veröffentlichen wir alle Release Ankündigungen in unserer [Discord Community](https://astro.build/chat) im `#announcements` Kanal. + +Obwohl nicht jeder Astro Release einenen eigenen Blogpost verdient, kannst du alle Änderungen für jedes Release in unserem detaillierten [`CHANGELOG.md` im Astro Repository](https://github.com/snowpackjs/astro/blob/main/packages/astro/CHANGELOG.md) nachlesen. + +## Fehlt etwas? + +Falls dir etwas in der Dokumentation fehlt oder du einen Teil verwirrend findest, [erstell bitte ein Issue](https://github.com/snowpackjs/astro/issues/new/choose) mit deinen Verbesserungsvorschlägen für die Dokumentation oder tweete an den [@astrodotbuild](https://twitter.com/astrodotbuild) Twitter account. + +Wir freuen uns, von dir zu hören. + +## Credit + +Diese Einführung basierte ursprünglich auf dem der Einführung von [React](https://reactjs.org/). diff --git a/docs/src/pages/es/getting-started.md b/docs/src/pages/group-1/es/getting-started.md similarity index 56% rename from docs/src/pages/es/getting-started.md rename to docs/src/pages/group-1/es/getting-started.md index 5de120149..2766c0a87 100644 --- a/docs/src/pages/es/getting-started.md +++ b/docs/src/pages/group-1/es/getting-started.md @@ -4,59 +4,59 @@ title: Empezando lang: es --- -Astro es un creador de sitios estáticos moderno. Aprende de qué trata Astro en nuestra [página principal](https://astro.build/) o nuestra [publicación de lanzamiento](https://astro.build/blog/introducing-astro). Esta página es una descripción general de la documentación de Astro y todos los recursos relacionados. +Astro es un creador de sitios estáticos moderno. Aprende de qué de trata Astro en nuestra [página principal](https://astro.build/) o nuestra [publicación](https://astro.build/blog/introducing-astro) de lanzamiento. Esta página es una descripción general de la documentación de Astro y todos los recursos relacionados. ¿Buscas una descripción general rápida de lo que es Astro? Visita nuestra [página](https://astro.build/) principal. -## Prueba Astro +## Intenta Astro -La forma más fácil de probar Astro es ejecutando `npm init astro` en un nuevo directorio en tu máquina. Nuestro asistente CLI te ayudará a comenzar un nuevo proyecto Astro. +La forma más fácil de probar Astro es corriendo `npm init astro` en un nuevo directorio en su máquina. Nuestro asistente CLI ayudará a comenzar un nuevo projecto astro. -Para comenzar con Astro en 5 sencillos y rápidos pasos, visita nuestra guía de [inicio rápido](/quick-start). +Para comenzar con Astro en 5 sencillos y rápidos pasos, visita nuestra guía [Inicio rápido](/quick-start). Alternativamente, lee nuestra guía de [instalación](/installation) para un recorrido completo de cómo configurar Astro. -### Playground en línea +### Playground En Línea -Si estás interesado en jugar con Astro en el navegador, puedes usar un playground de código en línea. Prueba nuestro template "Hola Mundo!" en [CodeSandbox](https://codesandbox.io/s/astro-template-hugb3). +Si estás interesado en jugar con Astro en el navegador, puedes usar un playground de código en línea. Trata nuestro modelo "Hola Mundo!" en [CodeSandbox](https://codesandbox.io/s/astro-template-hugb3). _Nota: Algunas caracteristicas (ex: Fast Refresh) actualmente están limitadas en CodeSandbox._ ## Aprende Astro -Todo tipo de personas vienen a Astro de diferentes orígenes trayendo consigo diferentes estilos de aprendizaje. Ya sea que prefieras un enfoque más teórico o práctico, esperamos que esta sección te resulte útil. +Todo tipo de personas vienen a Astro de diferentes orígenes trayendo consigo diferentes estilos de aprendizaje. Ya sea que prefieran un enfoque más teórico o práctico esperamos que esta sección le resulte útil. - Si prefieres **aprender haciendo**, comienza con nuestra biblioteca de [ejemplos](https://github.com/snowpackjs/astro/tree/main/examples). - Si prefieres **aprender conceptos paso a paso**, comienza con nuestros [conceptos básicos y guías](https://docs.astro.build/core-concepts/project-structure). Como cualquier tecnología desconocida, Astro viene con una ligera curva de aprendizaje. Sin embargo, con práctica y algo de paciencia, sabemos que lo dominarás en poco tiempo. -### Aprende la sintaxis de `.astro` +### Aprende el sintaxis de `.astro` -Cuando comienzes a aprender Astro, verás muchos archivos con la extensión `.astro`. Esta es la **sintaxis de componentes de Astro**: un formato de archivo especial similar a HTML que Astro usa para crear templates. Fue diseñado para que resulte familiar a cualquiera que tenga experiencia con HTML o JSX. +Cuando comienzes a aprender Astro, verás muchos archivos con la extensión `.astro`. Esta en la **Sintaxis de Componentes de Astro**: un formato de archivo especial similar a HTML que Astro usa para crear modelos. Fue diseñado para que cualquiera que tenga experiencia con HTML o JSX se sienta familiarizado. Nuestra guía sobre [componentes Astro](https://docs.astro.build/core-concepts/astro-components) presenta la sintaxis de Astro y es la mejor manera de aprender. -### Referencia de la API +### Referencia de API -Esta sección de documentación es útil cuando deseas obtener más detalles sobre una API de Astro en particular. Por ejemplo, la [referencia de configuración](https://docs.astro.build/reference/configuration-reference) enumera todas las opciones de configuración disponibles. La [referencia de componentes incluidos](https://docs.astro.build/reference/builtin-components) enumera todos los componentes básicos disponibles, como `` y ``. +Esta sección de documentación es útil cuando deseas obtener más detalles sobre un API de Astro en particular. Por ejemplo, la [Referencia de Configuración](https://docs.astro.build/reference/configuration-reference) enumera todas las opciones de configuración posibles disponibles para usted. La [Referencia de Componentes Integrados](https://docs.astro.build/reference/builtin-components) enumera todos los componentes disponibles, como `` y ``. ### Documentación versionada Esta documentación siempre refleja la última versión estable de Astro. Una vez que alcancemos la version v1.0, agregaremos la capacidad de ver documentación versionada. -## Mantenerse informado +## Mantenerse Informado La cuenta de Twitter [@astrodotbuild](https://twitter.com/astrodotbuild) es la fuente oficial de las actualizaciones del equipo de Astro. También publicamos anuncios de lanzamiento en nuestra comunidad de [Discord](https://astro.build/chat) en el canal de #announcements. -No todos los lanzamientos de Astro merecen su propia publicación en el blog, pero puedes encontrar un registro de cambios detallado para cada versión en el archivo [CHANGELOG.md](https://github.com/snowpackjs/astro/blob/main/packages/astro/CHANGELOG.md) en el repositorio de Astro. +No todos los lanzamientos de Astro merecen su propia publicación en el blog, pero pueden encontrar un registro de cambios detallado para cada versión en el archivo [CHANGELOG.md](https://github.com/snowpackjs/astro/blob/main/packages/astro/CHANGELOG.md) en el repositorio de Astro. -## ¿Falta algo? +## ¿Algo Falta? -Si falta algo en la documentación o si alguna parte te resulta confusa, por favor [abre una issue para la documentación](https://github.com/snowpackjs/astro/issues/new/choose) con tus sugerencias de mejora o menciona a la cuenta de Twitter [@astrodotbuild](https://twitter.com/astrodotbuild). ¡Nos encanta saber de ti! +Si falta algo en la documentación o si alguna parte le resulta confusa, por favor [presenta el problema](https://github.com/snowpackjs/astro/issues/new/choose) de la documentación con sugerencias de mejora, o tuitea a la cuenta de Twitter [@astrodotbuild](https://twitter.com/astrodotbuild). Nos encanta saber de ti! -## Créditos +## Crédito Esta guía de **Empezando** se basó originalmente en la guía de Empezando de [React](https://reactjs.org/). diff --git a/docs/src/pages/examples.md b/docs/src/pages/group-1/examples.md similarity index 100% rename from docs/src/pages/examples.md rename to docs/src/pages/group-1/examples.md diff --git a/docs/src/pages/fi/getting-started.md b/docs/src/pages/group-1/fi/getting-started.md similarity index 98% rename from docs/src/pages/fi/getting-started.md rename to docs/src/pages/group-1/fi/getting-started.md index df6f76432..f7694e436 100644 --- a/docs/src/pages/fi/getting-started.md +++ b/docs/src/pages/group-1/fi/getting-started.md @@ -37,7 +37,7 @@ Oppaamme [Astron komponenteista](/core-concepts/astro-components) esittelee uude ### API-luettelo -Tämä dokumentaation osa on hyödyllisin halutessasi oppia yksityiskohtia tietystä Astron rajapinnasta. Muun muassa [asetusluettelo](/reference/configuration-reference) listaa kaikki mahdolliset asetusvaihtoehdot. [Ydinkomponenttien luettelo](/reference/builtin-components) listaa kaikki käytössä olevat Astron mukana tulevat komponentit kuten `` ja ``. +Tämä dokumentaation osa on hyödyllisin halutessasi oppia yksityiskohtia tietystä Astron rajapinnasta. Muun muassa [asetusluettelo](/reference/configuration-reference) listaa kaikki mahdolliset asetusvaihtoehdot. [Ydinkomponenttien luettelo](/reference/builtin-components) listaa kaikki käytössä olevat Astron mukana tulevat komponentit kuten `` ja ``. ### Dokumentaation versioinnista diff --git a/docs/src/pages/fi/installation.md b/docs/src/pages/group-1/fi/installation.md similarity index 97% rename from docs/src/pages/fi/installation.md rename to docs/src/pages/group-1/fi/installation.md index 26f2e3884..129669908 100644 --- a/docs/src/pages/fi/installation.md +++ b/docs/src/pages/group-1/fi/installation.md @@ -60,9 +60,8 @@ Voit nyt vaihtaa oletuksena toimivan "scripts"-osion `npm init`in luomassa `pack ```diff "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" -+ "dev": "astro dev", -+ "build": "astro build", -+ "preview": "astro preview" ++ "start": "astro dev", ++ "build": "astro build" }, } ``` diff --git a/docs/src/pages/fi/quick-start.md b/docs/src/pages/group-1/fi/quick-start.md similarity index 98% rename from docs/src/pages/fi/quick-start.md rename to docs/src/pages/group-1/fi/quick-start.md index 6bc0d92e0..494deb262 100644 --- a/docs/src/pages/fi/quick-start.md +++ b/docs/src/pages/group-1/fi/quick-start.md @@ -18,7 +18,7 @@ npm init astro npm install # aloita kehittäminen! -npm run dev +npm start # kun olet valmis: luo oma staattinen sivustosi hakemistoon `dist/` npm run build @@ -33,7 +33,7 @@ Astro-sivuston käyttöönotto tuotannossa vaatii `/dist`-hakemiston (joka luoda Siirry takaisin komentoriville ja suorita tämä komento projektin hakemistossa: ```bash -npm run dev +npm start ``` Tämän jälkeen ohjelma on käynnissä osoitteessa [http://localhost:3000](http://localhost:3000). Avaa tämä URL selaimessa nähdäksesi viestin "Moi maailma!", jonka kopioimme edellisessä vaiheessa. diff --git a/docs/src/pages/getting-started.md b/docs/src/pages/group-1/getting-started.md similarity index 95% rename from docs/src/pages/getting-started.md rename to docs/src/pages/group-1/getting-started.md index 73ac8e0d7..cc7d9d688 100644 --- a/docs/src/pages/getting-started.md +++ b/docs/src/pages/group-1/getting-started.md @@ -11,7 +11,7 @@ Looking for a quick overview of what Astro is? [Visit our homepage.](https://ast The easiest way to try Astro is to run `npm init astro` in a new directory on your machine. Our CLI wizard will assist you in starting a new Astro project. -To get started with Astro in 5 quick and easy steps, visit our [Quick-Start guide](quick-start). +To get started with Astro in 5 quickly and easy steps, visit our [Quick-Start guide](quick-start). Alternatively, read our [Installation Guide](/installation) for a full walk-through on getting set up with Astro. @@ -38,7 +38,7 @@ Our helpful guide on [Astro components](/core-concepts/astro-components) introdu ### API Reference -This documentation section is useful when you want to learn more details about a particular Astro API. For example, [Configuration Reference](/reference/configuration-reference) lists all possible configuration options available to you. [Built-in Components Reference](/reference/builtin-components) lists all available core components, like `` and ``. +This documentation section is useful when you want to learn more details about a particular Astro API. For example, [Configuration Reference](/reference/configuration-reference) lists all possible configuration options available to you. [Built-in Components Reference](/reference/builtin-components) lists all available core components, like `` and ``. ### Versioned Documentation diff --git a/docs/src/pages/guides/data-fetching.md b/docs/src/pages/group-1/guides/data-fetching.md similarity index 100% rename from docs/src/pages/guides/data-fetching.md rename to docs/src/pages/group-1/guides/data-fetching.md diff --git a/docs/src/pages/guides/deploy.md b/docs/src/pages/group-1/guides/deploy.md similarity index 97% rename from docs/src/pages/guides/deploy.md rename to docs/src/pages/group-1/guides/deploy.md index ff0c30d95..de1161945 100644 --- a/docs/src/pages/guides/deploy.md +++ b/docs/src/pages/group-1/guides/deploy.md @@ -13,8 +13,7 @@ The following guides are based on some shared assumptions: { "scripts": { "start": "astro dev", - "build": "astro build", - "preview": "astro preview" + "build": "astro build" } } ``` @@ -69,15 +68,15 @@ By default, the build output will be placed at `dist/`. You may deploy this `dis ### GitHub Actions -1. In the astro project repo, create `gh-pages` branch then go to Settings > Pages and set to `gh-pages` branch for GitHub Pages and set directory to `/` (root). +1. In the astro project repo, create `gh-pages` branch then go to Settings > Pages and set to `gh-pages` branch for Github Pages and set directory to `/` (root). 2. Set the correct `buildOptions.site` in `astro.config.mjs`. 3. Create the file `.github/workflows/main.yml` and add in the yaml below. Make sure to edit in your own details. -4. In GitHub go to Settings > Developer settings > Personal Access tokens. Generate a new token with repo permissions. +4. In Github go to Settings > Developer settings > Personal Access tokens. Generate a new token with repo permissions. 5. In the astro project repo (not \.github.io) go to Settings > Secrets and add your new personal access token with the name `API_TOKEN_GITHUB`. 6. When you push changes to the astro project repo CI will deploy them to \.github.io for you. ```yaml -# Workflow to build and deploy to your GitHub Pages repo. +# Workflow to build and deploy to your Github Pages repo. # Edit your project details here. # Remember to add API_TOKEN_GITHUB in repo Settings > Secrets as well! diff --git a/docs/src/pages/guides/imports.md b/docs/src/pages/group-1/guides/imports.md similarity index 100% rename from docs/src/pages/guides/imports.md rename to docs/src/pages/group-1/guides/imports.md diff --git a/docs/src/pages/guides/markdown-content.md b/docs/src/pages/group-1/guides/markdown-content.md similarity index 75% rename from docs/src/pages/guides/markdown-content.md rename to docs/src/pages/group-1/guides/markdown-content.md index 05d59c1ff..bcb549096 100644 --- a/docs/src/pages/guides/markdown-content.md +++ b/docs/src/pages/group-1/guides/markdown-content.md @@ -13,7 +13,7 @@ Also, Astro supports third-party plugins for Markdown. You can provide your plug > **Note:** Enabling custom `remarkPlugins` or `rehypePlugins` removes Astro's built-in support for [GitHub-flavored Markdown](https://github.github.com/gfm/) support, [Footnotes](https://github.com/remarkjs/remark-footnotes) syntax, [Smartypants](https://github.com/silvenon/remark-smartypants), [Remark-slug](https://github.com/remarkjs/remark-slug). You must explicitly add these plugins to your `astro.config.mjs` file, if desired. -### Add a Markdown plugin in Astro +## Add a Markdown plugin in Astro If you want to add a plugin, you need to install the npm package dependency in your project and then update the `markdownOptions.remarkPlugins` or `markdownOptions.rehypePlugins` depends on what plugin you want to have: @@ -49,73 +49,65 @@ export default { }; ``` -## Markdown Pages +### Markdown Pages -Astro treats any `.md` files inside of the `/src/pages` directory as pages. These files can contain frontmatter, but are otherwise processed as plain markdown files and do not support components. If you're looking to embed rich components in your markdown, take a look at the [Markdown Component](#astros-markdown-component) section. +Astro treats any `.md` files inside of the `/src/pages` directory as pages. These pages are processed as plain markdown files and do not support components. If you're looking to embed rich components in your markdown, take a look at the [Markdown Component](#astros-markdown-component) section. -### Layouts +`layout` -Markdown pages have a special frontmatter property for `layout`. This defines the relative path to an `.astro` component which should wrap your Markdown content, for example a [Layout](/core-concepts/layouts) component. All other frontmatter properties defined in your `.md` page will be exposed to the component as properties of the `content` prop. The rendered Markdown content is placed into the default `` element. +The only special Frontmatter key is `layout`, which defines the relative path to an `.astro` component which should wrap your Markdown content. + +`src/pages/index.md` ```jsx -// src/pages/index.md --- -layout: ../../layouts/BaseLayout.astro -title: My cool page +layout: ../layouts/main.astro --- # Hello World! ``` +Layout files are normal `.astro` components. Any Frontmatter defined in your `.md` page will be exposed to the Layout component as the `content` prop. `content` also has an `astro` key which holds special metadata about your file, like the complete Markdown `source` and a `headings` object. + +Keep in mind that the only guaranteed variables coming from the `content` prop object are `astro` and `url`. An example of what a blog post `content` object might look like is as follows: + +```json +{ + /** Frontmatter from blog post + "title": "", + "date": "", + "author": "", + "description": "", + **/ + "astro": { + "headers": [], + "source": "" + }, + "url": "" +} +``` + +The rendered Markdown content is placed into the default `` element. + +`src/layouts/main.astro` + ```jsx -// src/layouts/BaseLayout.astro --- const { content } = Astro.props; --- + {content.title} - + ``` -For Markdown files, the `content` prop also has an `astro` property which holds special metadata about the page such as the complete Markdown `source` and a `headers` object. An example of what a blog post `content` object might look like is as follows: - -```json -{ - /** Frontmatter from a blog post - "title": "Astro 0.18 Release", - "date": "Tuesday, July 27 2021", - "author": "Matthew Phillips", - "description": "Astro 0.18 is our biggest release since Astro launch.", - **/ - "astro": { - "headers": [ - { - "depth": 1, - "text": "Astro 0.18 Release", - "slug": "astro-018-release" - }, - { - "depth": 2, - "text": "Responsive partial hydration", - "slug": "responsive-partial-hydration" - } - /* ... */ - ], - "source": "# Astro 0.18 Release\\nA little over a month ago, the first public beta [...]" - }, - "url": "" -} -``` - -> Keep in mind that the only guaranteed properties coming from the `content` prop are `astro` and `url`. - -## Astro's Markdown Component +### Astro's Markdown Component Astro has a dedicated component used to let you render your markdown as HTML components. This is a special component that is only exposed to `.astro` files. To use the `` component, within your frontmatter block use the following import statement: @@ -148,7 +140,7 @@ import { Markdown } from 'astro/components'; // For now, this import _must_ be named "Markdown" and _must not_ be wrapped with a custom component // We're working on easing these restrictions! import { Markdown } from 'astro/components'; -import Layout from '../layouts/main.astro'; +import Layout from '../../layouts/main.astro'; import MyFancyCodePreview from '../components/MyFancyCodePreview.tsx'; const expressions = 'Lorem ipsum'; @@ -184,7 +176,7 @@ const expressions = 'Lorem ipsum'; ```` -## Remote Markdown +### Remote Markdown If you have Markdown in a remote source, you may pass it directly to the Markdown component through the `content` attribute. For example, the example below fetches the README from Snowpack's GitHub repository and renders it as HTML. @@ -216,11 +208,11 @@ const content = await fetch('https://raw.githubusercontent.com/snowpackjs/snowpa Here we have some __Markdown__ code. We can also dynamically render content from remote places. - + ``` -## Security FAQs +### Security FAQs **Aren't there security concerns to rendering remote markdown directly to HTML?** diff --git a/docs/src/pages/guides/publish-to-npm.md b/docs/src/pages/group-1/guides/publish-to-npm.md similarity index 95% rename from docs/src/pages/guides/publish-to-npm.md rename to docs/src/pages/group-1/guides/publish-to-npm.md index f5533d864..4f6ab402f 100644 --- a/docs/src/pages/guides/publish-to-npm.md +++ b/docs/src/pages/group-1/guides/publish-to-npm.md @@ -92,7 +92,6 @@ Looking for components already made by the community? Here are the current available community developed Astro components. - [Astro Static Tweet](https://www.npmjs.com/package/@rebelchris/astro-static-tweet) ~ A component to embed tweets as static HTML so you don't have to load the Twitter JavaScripts. -- [Accessible Astro Components](https://www.npmjs.com/package/accessible-astro-components) ~ A set of accessible front-end components such as Accordions, Modals, Toggle Buttons and more. You can also [search npm for astro components.](https://www.npmjs.com/search?q=keywords%3Aastro-component) diff --git a/docs/src/pages/guides/styling.md b/docs/src/pages/group-1/guides/styling.md similarity index 92% rename from docs/src/pages/guides/styling.md rename to docs/src/pages/group-1/guides/styling.md index 7366cc107..ed1ebc1f6 100644 --- a/docs/src/pages/guides/styling.md +++ b/docs/src/pages/group-1/guides/styling.md @@ -114,12 +114,10 @@ Astro also supports [Sass][sass] out-of-the-box. To enable for each framework: 💁‍ Sass is great! If you haven't used Sass in a while, please give it another try. The new and improved [Sass Modules][sass-use] are a great fit with modern web development, and it's blazing-fast since being rewritten in Dart. And the best part? **You know it already!** Use `.scss` to write familiar CSS syntax you're used to, and only sprinkle in Sass features if/when you need them.' -**Note**: If you use .scss files rather than .css files, your stylesheet links should still point to .css files because of Astro’s auto-compilation process. When Astro “needs” the styling files, it’ll be “looking for” the final .css file(s) that it compiles from the .scss file(s). For example, if you have a .scss file at `./src/styles/global.scss`, use this link: `` — **not** ``. +**Note**: If you use .scss files rather than .css files, your stylesheet links should still point to .css files because of Astro’s auto-compilation process. When Astro “needs” the styling files, it’ll be “looking for” the final .css file(s) that it compiles from the .scss file(s). For example, if you have a .scss file at `./public/style/global.scss`, use this link: `` — **not** ``. ### 🍃 Tailwind -> Note that Astro's Tailwind support _only_ works with Tailwind JIT mode. - Astro can be configured to use [Tailwind][tailwind] easily! Install the dependencies: ``` @@ -148,27 +146,16 @@ Be sure to add the config path to `astro.config.mjs`, so that Astro enables JIT }; ``` -Now you're ready to write Tailwind! Our recommended approach is to create a `src/styles/global.css` file (or whatever you‘d like to name your global stylesheet) with [Tailwind utilities][tailwind-utilities] like so: +Now you're ready to write Tailwind! Our recommended approach is to create a `public/global.css` file (or whatever you‘d like to name your global stylesheet) with [Tailwind utilities][tailwind-utilities] like so: ```css -/* src/styles/global.css */ +/* public/global.css */ @tailwind base; @tailwind components; @tailwind utilities; ``` -As an alternative to `src/styles/global.css`, You may also add Tailwind utilities to individual `pages/*.astro` components in ` +
+``` + +```html + + + + + + + ... + + +``` + +Using ` + +
I'm a scoped style and only apply to this component
+

I have both scoped and global styles

+``` + +To include every selector in a ` + + + +
I'm a scoped style and only apply to this component
+

I have both scoped and global styles

+``` + +📚 Read our full guide on [Astro component syntax](/core-concepts/astro-components#css-styles) to learn more about using the ` +``` + +### 🎭 PostCSS + +[PostCSS](https://postcss.org/) is a popular CSS transpiler with support for [a huge ecosystem of plugins.](https://github.com/postcss/postcss#plugins) + +**To use PostCSS with Snowpack:** add the [@snowpack/plugin-postcss](https://www.npmjs.com/package/@snowpack/plugin-postcss) plugin to your project. + +```diff +// snowpack.config.js +"plugins": [ ++ "@snowpack/plugin-postcss" +] +``` + +PostCSS requires a [`postcss.config.js`](https://github.com/postcss/postcss#usage) file in your project. By default, the plugin looks in the root directory of your project, but you can customize this yourself with the `config` option. See [the plugin README](https://www.npmjs.com/package/@snowpack/plugin-postcss) for all available options. + +```js +// postcss.config.js +// Example (empty) postcss config file +module.exports = { + plugins: [ + // ... + ], +}; +``` + +Be aware that this plugin will run on all CSS in your project, including any files that compiled to CSS (like `.scss` Sass files, for example). + +## Bundling + +All CSS is minified and bundled automatically for you in running `astro build`. Without getting too in the weeds, the general rules are: + +- If a style only appears on one route, it's only loaded for that route (`/_astro/[page]-[hash].css`) +- If a style appears on multiple routes, it's deduplicated into a `/_astro/common-[hash].css` bundle +- All styles are hashed according to their contents (the hashes only change if the contents do!) + +We'll be expanding our styling optimization story over time, and would love your feedback! If `astro build` generates unexpected styles, or if you can think of improvements, [please open an issue][issues]. + +_Note: be mindful when some page styles get extracted to the "common" bundle, and some page styles stay on-page. For most people this may not pose an issue, but when part of your styles are bundled they technically may load in a different order and your cascade may be different. While this problem isn't unique to Astro and is present in almost any CSS bundling process, it can be unexpected if you're not anticipating it. Be sure to inspect your final production build, and please [report any issues][issues] you may come across._ + +## Advanced Styling Architecture + +Too many development setups take a hands-off approach to CSS, or at most leave you with only contrived examples that don't get you very far. Telling developers "Use whatever styling solution you want!" is a nice thought that rarely works out in practice. Few styling approaches lend themselves to every setup. Astro is no different—certain styling approaches _will_ work better than others. + +An example to illustrate this: Astro removes runtime JS (even the core framework if possible). Thus, depending on Styled Components for all your styles would be bad, as that would require React to load on pages where it's not needed. Or at best, you'd get a "[FOUC][fouc]" as your static HTML is served but the user waits for JavaScript to download and execute. Or consider a second example at the opposite end of the spectrum: _BEM_. You _can_ use a completely-decoupled [BEM][bem] or [SMACSS][smacss] approach in Astro. But that's a lot of manual maintenance you can avoid, and it leaves out a lof of convenience of [Astro components](/core-concepts/astro-components). + +We think there's a great middle ground between intuitive-but-slow CSS-in-JS and fast-but-cumbersome global CSS: **Hybrid Scoped + Utility CSS**. This approach works well in Astro, is performant for users, and will be the best styling solution in Astro _for most people_ (provided you're willing to learn a little). So as a quick recap: + +**This approach is good for…** + +- Developers wanting to try out something new in regard to styling +- Developers that would appreciate some strong opinions in CSS architecture + +**This approach is **NOT** good for…** + +- Developers that already have strong opinions on styling, and want to control everything themselves + +Read on if you're looking for some strong opinions 🙂. We'll describe the approach by enforcing a few key rules that should govern how you set your styles: + +### Hybrid Scoped + Utility CSS + +#### Scoped styles + +You don't need an explanation on component-based design. You already know that reusing components is a good idea. And it's this idea that got people used to concepts like [Styled Components][styled-components] and [Styled JSX][styled-jsx]. But rather than burden your users with slow load times of CSS-in-JS, Astro has something better: **built-in scoped styles.** + +```jsx +--- +// src/components/Button.astro --> +--- + + +``` + +_Note: all the examples here use `lang="scss"` which is a great convenience for nesting, and sharing [colors and variables][sass-use], but it's entirely optional and you may use normal CSS if you wish._ + +That `.btn` class is scoped within that component, and won't leak out. It means that you can **focus on styling and not naming.** Local-first approach fits in very well with Astro's ESM-powered design, favoring encapsulation and reusability over global scope. While this is a simple example, it should be noted that **this scales incredibly well.** And if you need to share common values between components, [Sass' module system][sass-use] also gets our recommendation for being easy to use, and a great fit with component-first design. + +By contrast, Astro does allow global styles via the `:global()` and ` + + +``` + +This is undesirable because now `