simple benchmark
This commit is contained in:
parent
e686c3c504
commit
bcdfec1aa5
781 changed files with 87434 additions and 2356 deletions
|
@ -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
|
||||
<script hoist>
|
||||
// Anything goes here!
|
||||
</script>
|
||||
```
|
||||
|
||||
## 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
|
||||
<img src="../images/penguin.png" />
|
||||
```
|
||||
|
||||
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
|
||||
<img src={Astro.resolve('../images/penguin.png')} />
|
||||
```
|
||||
|
||||
## 0.0.4
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- adc767c5: change Spanish translations for Getting Started page
|
||||
|
||||
## 0.0.3
|
||||
|
||||
### Patch Changes
|
||||
|
|
|
@ -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.
|
||||
|
|
|
@ -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",
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
|
|
@ -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) > * + * {
|
||||
|
|
|
@ -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 {
|
||||
|
|
|
@ -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';
|
||||
|
|
|
@ -1,8 +1,6 @@
|
|||
<!-- Global Metadata -->
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width">
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg"/>
|
||||
<link rel="alternate icon" type="image/x-icon" href="/favicon.ico" />
|
||||
<link rel="sitemap" href="/sitemap.xml"/>
|
||||
|
||||
<!-- Global CSS -->
|
||||
|
@ -30,10 +28,10 @@
|
|||
</script>
|
||||
|
||||
<!-- Global site tag (gtag.js) - Google Analytics -->
|
||||
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-130280175-15"></script>
|
||||
<script async src="https://www.googletagmanager.com/gtag/js?id=G-TEL60V1WM9"></script>
|
||||
<script>
|
||||
window.dataLayer = window.dataLayer || [];
|
||||
function gtag(){dataLayer.push(arguments);}
|
||||
gtag('js', new Date());
|
||||
gtag('config', 'UA-130280175-15');
|
||||
</script>
|
||||
gtag('config', 'G-TEL60V1WM9');
|
||||
</script>
|
|
@ -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;
|
|||
<link rel="canonical" href={canonicalURL}/>
|
||||
|
||||
<!-- OpenGraph Tags -->
|
||||
<meta property="og:title" content={content.title ?? SITE.title}/>
|
||||
<meta property="og:title" content={formattedContentTitle}/>
|
||||
<meta property="og:type" content="article"/>
|
||||
<meta property="og:url" content={canonicalURL}/>
|
||||
<meta property="og:locale" content={content.ogLocale ?? OPEN_GRAPH.locale}/>
|
||||
|
@ -29,7 +27,7 @@ const imageAlt = content?.image?.alt ?? OPEN_GRAPH.image.alt;
|
|||
<!-- Twitter Tags -->
|
||||
<meta name="twitter:card" content="summary_large_image"/>
|
||||
<meta name="twitter:site" content={OPEN_GRAPH.twitter}/>
|
||||
<meta name="twitter:title" content={content.title ?? SITE.title}/>
|
||||
<meta name="twitter:title" content={formattedContentTitle}/>
|
||||
<meta name="twitter:description" content={content.description ? content.description : SITE.description}/>
|
||||
<meta name="twitter:image" content={canonicalImageSrc}/>
|
||||
<meta name="twitter:image:alt" content={imageAlt}/>
|
||||
|
|
|
@ -23,7 +23,6 @@ const lang = currentPage && getLanguageFromURL(currentPage);
|
|||
|
||||
|
||||
.logo {
|
||||
direction: ltr;
|
||||
display: flex;
|
||||
overflow: hidden;
|
||||
width: 30px;
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -68,25 +68,7 @@ const LanguageSelect: FunctionalComponent<{ lang: string }> = ({ lang }) => {
|
|||
<span>简体中文</span>
|
||||
</option>
|
||||
<option value="zh-TW">
|
||||
<span>正體中文</span>
|
||||
</option>
|
||||
<option value="bg">
|
||||
<span>Български</span>
|
||||
</option>
|
||||
<option value="fr">
|
||||
<span>Français</span>
|
||||
</option>
|
||||
<option value="bn">
|
||||
<span>বাংলা</span>
|
||||
</option>
|
||||
<option value="kr">
|
||||
<span>한국어</span>
|
||||
</option>
|
||||
<option value="ar">
|
||||
<span>العربية</span>
|
||||
</option>
|
||||
<option value="da">
|
||||
<span>Dansk</span>
|
||||
<span>繁体中文</span>
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
|
|
|
@ -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;
|
||||
|
|
|
@ -51,7 +51,7 @@ export default function Search() {
|
|||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
<span className="search-placeholder">Search</span>
|
||||
<span>Search</span>
|
||||
<span className="search-hint">
|
||||
<span className="sr-only">Press </span>
|
||||
<kbd>/</kbd>
|
||||
|
|
|
@ -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) {
|
||||
|
|
|
@ -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;
|
||||
---
|
||||
<style>
|
||||
.content {
|
||||
|
@ -46,14 +38,4 @@ const previous = index !== -1 ? (index === 0 ? null : links[index - 1]) : null;
|
|||
<nav class="block sm:hidden">
|
||||
<MoreMenu editHref={githubEditUrl}/>
|
||||
</nav>
|
||||
{
|
||||
(previous || next) && <aside>
|
||||
{
|
||||
previous && <div>Previous Article: <a rel="prev" href={new URL(previous.link, Astro.site).pathname}>{previous.text}</a></div>
|
||||
}
|
||||
{
|
||||
next && <div>Next Article: <a rel="next" href={new URL(next.link, Astro.site).pathname}>{next.text}</a></div>
|
||||
}
|
||||
</aside>
|
||||
}
|
||||
</article>
|
|
@ -64,5 +64,5 @@ const {editHref} = Astro.props;
|
|||
</li>
|
||||
</ul>
|
||||
<div style="margin: 2rem 0; text-align: center;">
|
||||
<ThemeToggleButton client:visible />
|
||||
<ThemeToggleButton client:idle />
|
||||
</div>
|
||||
|
|
|
@ -9,21 +9,17 @@ export const SIDEBAR = {
|
|||
|
||||
{ text: 'Basics', header: true },
|
||||
{ text: 'Project Structure', link: 'core-concepts/project-structure' },
|
||||
{ text: 'Component Syntax', link: 'core-concepts/astro-components' },
|
||||
{ text: 'Components', link: 'core-concepts/astro-components' },
|
||||
{ text: 'Pages', link: 'core-concepts/astro-pages' },
|
||||
{ text: 'Layouts', link: 'core-concepts/layouts' },
|
||||
{ text: 'Routing', link: 'core-concepts/routing' },
|
||||
{ text: 'Collections', link: 'core-concepts/collections' },
|
||||
{ text: 'Partial Hydration', link: 'core-concepts/component-hydration' },
|
||||
|
||||
{ text: 'Guides', header: true },
|
||||
{ text: 'Styling & CSS', link: 'guides/styling' },
|
||||
{ text: 'Markdown', link: 'guides/markdown-content' },
|
||||
{ text: 'Debugging', link: 'guides/debugging' },
|
||||
{ text: 'Data Fetching', link: 'guides/data-fetching' },
|
||||
{ text: 'Pagination', link: 'guides/pagination' },
|
||||
{ text: 'RSS', link: 'guides/rss' },
|
||||
{ text: 'Markdown', link: 'guides/markdown-content' },
|
||||
{ text: 'Supported Imports', link: 'guides/imports' },
|
||||
{ text: 'Aliases', link: 'guides/aliases' },
|
||||
{ text: 'Deploy a Website', link: 'guides/deploy' },
|
||||
{ text: 'Publish a Component', link: 'guides/publish-to-npm' },
|
||||
|
||||
|
@ -61,43 +57,10 @@ export const SIDEBAR = {
|
|||
{ text: '快速入门', link: 'zh-CN/quick-start' },
|
||||
{ text: '安装指南', link: 'zh-CN/installation' },
|
||||
{ text: '模板样例', link: 'zh-CN/examples' },
|
||||
{
|
||||
text: 'Astro 对比其他框架',
|
||||
link: 'zh-CN/comparing-astro-vs-other-tools',
|
||||
},
|
||||
],
|
||||
'zh-TW': [
|
||||
{ text: '設定', header: true },
|
||||
{ text: '新手上路', link: 'zh-TW/getting-started' },
|
||||
{ text: '快速開始', link: 'zh-TW/quick-start' },
|
||||
{ text: '安裝', link: 'zh-TW/installation' },
|
||||
{ text: '範例', link: 'zh-TW/examples' },
|
||||
],
|
||||
bg: [
|
||||
{ text: 'Главни', header: true },
|
||||
{ text: 'Започваме!', link: 'bg/getting-started' },
|
||||
],
|
||||
fr: [
|
||||
{ text: 'Bienvenue', header: true },
|
||||
{ text: 'Bien démarrer', link: 'fr/getting-started' },
|
||||
{ text: 'Démarrage rapide', link: 'fr/quick-start' },
|
||||
{ text: 'Installation', link: 'fr/installation' },
|
||||
],
|
||||
bn: [
|
||||
{ text: 'সেটআপ', header: true },
|
||||
{ text: 'শুরু করুন', link: 'bn/getting-started' },
|
||||
],
|
||||
kr: [
|
||||
{ text: '환영합니다', header: true },
|
||||
{ text: '시작하기', link: 'kr/getting-started' },
|
||||
],
|
||||
ar: [
|
||||
{ text: 'التهيئة', header: true },
|
||||
{ text: 'باشر البدأ', link: 'ar/getting-started' },
|
||||
],
|
||||
da: [
|
||||
{ text: 'Velkommen', header: true },
|
||||
{ text: 'Introduktion', link: 'da/getting-started' },
|
||||
{ text: '起步', header: true },
|
||||
{ text: '入門指南', link: 'zh-TW/getting-started' },
|
||||
],
|
||||
};
|
||||
|
||||
|
|
|
@ -12,14 +12,13 @@ const { content = {} } = Astro.props;
|
|||
const currentPage = Astro.request.url.pathname;
|
||||
const currentFile = `src/pages${currentPage.replace(/\/$/, "")}.md`;
|
||||
const githubEditUrl = `https://github.com/snowpackjs/astro/blob/main/docs/${currentFile}`;
|
||||
const formatTitle = (content, SITE) => content.title ? `${content.title} 🚀 ${SITE.title}` : SITE.title;
|
||||
---
|
||||
|
||||
<html dir="{content.dir ?? 'ltr'}" lang="{content.lang ?? 'en-us'}" class="initial">
|
||||
<head>
|
||||
<HeadCommon />
|
||||
<HeadSEO {content} canonicalURL={Astro.request.canonicalURL} />
|
||||
<title>{formatTitle(content, SITE)}</title>
|
||||
<title>{content.title ? `${content.title} 🚀 ${SITE.title}` : SITE.title}</title>
|
||||
<style>
|
||||
body {
|
||||
width: 100%;
|
||||
|
@ -66,7 +65,7 @@ const formatTitle = (content, SITE) => content.title ? `${content.title} 🚀 ${
|
|||
:global(.mobile-sidebar-toggle) {
|
||||
overflow: hidden;
|
||||
}
|
||||
:global(.mobile-sidebar-toggle #grid-left) {
|
||||
:global(.mobile-sidebar-toggle) #grid-left {
|
||||
display: block;
|
||||
top: 2rem;
|
||||
}
|
||||
|
@ -111,7 +110,7 @@ const formatTitle = (content, SITE) => content.title ? `${content.title} 🚀 ${
|
|||
<LeftSidebar currentPage={currentPage} />
|
||||
</aside>
|
||||
<div id="grid-main">
|
||||
<PageContent content={content} githubEditUrl={githubEditUrl} currentPage={currentPage}>
|
||||
<PageContent content={content} githubEditUrl={githubEditUrl}>
|
||||
<slot />
|
||||
</PageContent>
|
||||
</div>
|
||||
|
|
|
@ -1,64 +0,0 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: باشر بالبدأ
|
||||
lang: ar
|
||||
dir: rtl
|
||||
---
|
||||
|
||||
Astro هو باني موقع ثابت. تعرف أكثر حول ماهية Astro من خلال [صفحتنا الرئيسية](https://astro.build/) أو نشرة [الإصدارات](https://astro.build/blog/introducing-astro). تُعد هذه الصفحة نُبذة موجزة للتوثيق الخاص بـAstro وأيضًا لكل المصادر التي تتعلق به.
|
||||
|
||||
إن كنت تتطلع عن ملخص سريع حول ما هو Astro بشكلٍ عام؟ [تفقد صفحتنا الرئيسية.](https://astro.build/blog/introducing-astro)
|
||||
|
||||
## جرب Astro
|
||||
|
||||
أبسط طريقة لتجرب Astro هي بتنفيذ أمر `npm init astro` في داخل مُجلد جديد على جهازك، وسيقوم Astro CLI بمُساعدتك على بدأ مشروع Astro جديد.
|
||||
|
||||
لتباشر البدأ باستخدام Astro من خلال 5 خطوات سريعة وبسيطة، تفقد [دليل البدأ-بسرعة](quick-start).
|
||||
|
||||
أو إقرأ [دليل التثبيت](/installation) إن كنت تريد الغوص في عملية تهيئة Astro.
|
||||
|
||||
### جربه على المُتصفح
|
||||
|
||||
إن كنت مهتمًا وتريد اللعب وتجربة Astro على المتصفح، بمقدورك استخدام online code playground، جرب قالب مشروعنا "Hello World" على [CodeSandbox](https://codesandbox.io/s/astro-template-hugb3).
|
||||
|
||||
_ملحوظة: بعض المُميزات مُقتصرة على CodeSandbx (مثلاً: التحديث السريع "Fast Refresh") حاليًا._
|
||||
|
||||
## تعلمُ Astro
|
||||
|
||||
يأتي مختلف الأشخاص من خلفياتِ تعلم مُختلفة إلى Astro، أيًا كانت طريقة التعليم التي تفضلها سواءً أكنت تفضل الطريقة النظرية أو الطريقة العملية، نتمنى أن تجد هذا القسم مفيدًا.
|
||||
|
||||
- إن كُنت تُفضل **التعلم من خلال التجربة العملية**، أبدأ من خلال [مكتبتنا للأمثلة](https://github.com/snowpackjs/astro/tree/main/examples).
|
||||
- إن كُنت تُفضل **التعلم من خلال الفهم خطوةً بخطوة**، أبدأ من خلال [دليل المفاهيم الأساسية والإرشادات](/core-concepts/project-structure).
|
||||
|
||||
مثل أي تقنيةٍ ليست بمألوفة، Astro يأتيك بمنحنى تعليمي مختلف بعض الشيء، ولكن على أي حال، مع بعض الصبر والممارسة، نحن متأكدون بأنك _ستتأقلم معه_ في وقتٍ هين دون أن تشعر.
|
||||
|
||||
### تعلمُ تركيب <code dir="ltr">.astro</code> النحوي (syntax)
|
||||
|
||||
مع بدأ تعلمك لـAstro ستلاحظ العديد من الملفات التي تنتهي بصيغة <code dir="ltr">.astro</code> هي ملفات مكتوبة بـ Astro’s Component Syntax والتي تعد: طريقة كتابة مشابهة جدًا لملفات HTML يستخدمها Astro في القوالب.
|
||||
صممت هذه الصيغة لتكون قريبة ومشابهة للـ HTML و JSX، إن كنت تعرف أحدهما فستتأقلم مع <code dir="ltr">.astro</code> بسهولة.
|
||||
|
||||
تفقد دليلنا المساعد [مكونات Astro](/core-concepts/astro-components) سيكون مدخل يساعدك على تعلم Astro syntax، ويعد أفضل طريقة للتعلم.
|
||||
|
||||
### مرجع للـAPI
|
||||
|
||||
يُفيدك هذا الجزء من التوثيق حينما تريد الإطلاع أكثر بشأن تفاصيل Astro API. على سبيل المثال، يتضمن [مرجع الإعداد](/reference/configuration-reference) قائمة لكل الإعدادات الممكنة المتاحة لكي تستخدمها. [المكونات المصممة مسبقًا](/reference/builtin-components) تتضمن قائمة بكل العناصر الرئيسية مثل <span dir="ltr">`<Markdown />` و `<Prism />`</span>.
|
||||
|
||||
### إصدارات التوثيق
|
||||
|
||||
هذا التوثيق يُسلط الضوء دومًا على أخر إصدار مستقر من Astro، وريثما نصل إلى إصدار 1.0 الرئيسي سنقوم بإضافة القابلية لتصفح اللإصدارات المختلفة من التوثيق.
|
||||
|
||||
## أبقى مُطلعًا
|
||||
|
||||
حساب [@astrodotbuild](https://twitter.com/astrodotbuild) على تويتر هو المصدر الرسمي لأخر المُستجدات من فريق Astro.
|
||||
|
||||
ونحن أيضًا نُعد نشرة إصدارات ونعلن عنها في [مُجتمعنا على ديسكورد](https://astro.build/chat) على قناة <span dir="ltr">#announcements</span>
|
||||
|
||||
ليست كل إصدارات Astro تملك تدوينة نشرةٍ خاصة بها، لكن ستجد سجلًا للتغيرات في ملف [`CHANGELOG.md` في مستودع Astro](https://github.com/snowpackjs/astro/blob/main/packages/astro/CHANGELOG.md).
|
||||
|
||||
## شيءٌ ما ناقص؟
|
||||
|
||||
إن كان هناك شيءُ ما غير مُوثق أو لو كنت تشعر بالحيرة والإرتباك من جزءٍ معين في التوثيق، لا تتردد في [رفع طلب خطبٌ ما في ملف التوثيق](https://github.com/snowpackjs/astro/issues/new/choose)، مع اقتراحك للتحسين، أو قم بتغريد تغريدةٍ إلى حسابنا على تويتر [@astrodotbuild](https://twitter.com/astrodotbuild)، نحب سماع آرائك!
|
||||
|
||||
## التَقدِير
|
||||
|
||||
دليل باشر بالبدأ معتمدٌ على دليل البدأ الخاص بـ[React](https://ar.reactjs.org/).
|
|
@ -1,62 +0,0 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Започваме!
|
||||
---
|
||||
|
||||
Astro е модерен builder за статични сайтове. Научете всичко за Astro от [нашата начална страница](https://astro.build/) или от [release поста](https://astro.build/blog/introducing-astro). Тази страница е оглед на документацията на Astro и всички свързани ресурси.
|
||||
|
||||
За бърз оглед на Astro, посетете нашата [начална страница](https://astro.build).
|
||||
|
||||
## Пробвайте Astro
|
||||
|
||||
Най-лесният начин да пробвате Astro е да изпълните `npm init astro` в нова локална директория. Нашият CLI Wizard ще Ви помогне да започнете нов Astro проект.
|
||||
|
||||
За да започнете с Astro в 5 бързи и лесни стъпки, посетете нашия [Гид за бърз старт](quick-start).
|
||||
|
||||
Алтернативно, можете да прочетете нашия [Инсталационен гид](/installation) за всичко относно настройката на Astro.
|
||||
|
||||
### Онлайн площадки (playgrounds)
|
||||
|
||||
Ако искате да си експериментирате с Astro в браузъра, можете да използвате онлайн площадка за код. Пробвайте нашия "Hello World!" темплейт на [CodeSandbox](https://codesandbox.io/s/astro-template-hugb3).
|
||||
|
||||
_Бележка: някои функционалности (например: Fast Refresh) са лимитирани на CodeSandbox засега._
|
||||
|
||||
## Научете Astro
|
||||
|
||||
Всякакви видове хора с различни методи за обучение се ориентират към Astro. Независимо дали предпочитате по-теоретичен, или по-практически подход, ние се надяваме че ще намерите тази секция за полезна.
|
||||
|
||||
- Ако предпочитате да **учите чрез практика**, започнете с нашата [библиотека с примери](https://github.com/snowpackjs/astro/tree/main/examples).
|
||||
- Ако предпочитате да **учите концепции стъпка по стъпка**, започнете с нашите [базови концепции и гидове](/core-concepts/project-structure).
|
||||
|
||||
Като всяка непозната технология, Astro изисква известно време, за да се научи. Но с практика и малко търпение, ние сме сигурни, че _ще го схванете_ за нула време.
|
||||
|
||||
### Научете `.astro` синтаксис
|
||||
|
||||
Когато започнете да учите Astro, ще видите много файлове с разширение `.astro`. Това е **Компонентният синтаксис на Astro** -
|
||||
специален файлов формат наподобяващ HTML, който Astro използва за изграждане на страници (templating). Направен е, така че да е познат на всеки с HTML или JSX опит.
|
||||
|
||||
Нашият помощен гид за [Astro компонентите](/core-concepts/astro-components) Ви запознава със синтаксисът на Astro и е най-добрият начин да се научите.
|
||||
|
||||
### API Справка
|
||||
|
||||
Тази секция е полезна, когато искате да научите повече детайли относно даден Astro API. Например - [Конфигурационната справка](/reference/configuration-reference) изброява всички възможни конфигурационни опции. [Справката за вградени компоненти](/reference/builtin-components) изброява всички възможни базови (core) компоненти, като `<Markdown />` и `<Code />`.
|
||||
|
||||
### Версия на документацията
|
||||
|
||||
Тази документация винаги рефлектира последната стабилна версия на Astro. Когато пуснем версия 1.0, ще добавим опция за преглед на предишни или бъдещи версии.
|
||||
|
||||
## Бъдете информирани
|
||||
|
||||
Официалният източник за новини от екипа на Astro е Twitter акаунтът - [@astrodotbuild](https://twitter.com/astrodotbuild).
|
||||
|
||||
Публикуваме и съобщения относно нови версии в [нашия Discord сървър](https://astro.build/chat) в #announcements канала.
|
||||
|
||||
Не всяка нова версия на Astro заслужава собствен блог пост, но можете да намерите регистър на промените за всеки релийз в [`CHANGELOG.MD` файла, намиращ се в репото на Astro](https://github.com/snowpackjs/astro/blob/main/packages/astro/CHANGELOG.md).
|
||||
|
||||
## Нещо липсва?
|
||||
|
||||
Ако нещо липсва в документацията или намирате нещо за объркващо, моля [подайте го като issue за документацията](https://github.com/snowpackjs/astro/issues/new/choose) с Вашите предложения за подобрение или пуснете tweet към [@astrodotbuild](https://twitter.com/astrodotbuild). Обичаме да чуваме от Вас!
|
||||
|
||||
## Credit
|
||||
|
||||
Първоначално този гид е базиран на документацията на [React](https://reactjs.org/).
|
|
@ -1,61 +0,0 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: শুরু করুন
|
||||
---
|
||||
|
||||
Astro হচ্ছে একটি আধুনিক স্ট্যাটিক ওয়েবসাইট বিল্ডার। Astro সম্পর্কে বিস্তারিত জানুন [আমাদের হোমপেজ](https://astro.build/) থেকে অথবা [আমাদের রিলিজ পোস্ট](https://astro.build/blog/introducing-astro) থেকে। এই পেজটি Astro-এর ডকুমেন্টেশন এবং এ সম্পর্কিত সকল বিষয়ের একটি সারাংশ।
|
||||
|
||||
Astro-এর দ্রুত একটি সারসংক্ষেপ খুঁজছেন, [আমাদের হোমপেজ](https://astro.build) ভিসিট করুন।
|
||||
|
||||
## Astro ব্যবহার করুন
|
||||
|
||||
Astro ব্যবহার করার সবচেয়ে সহজ উপায় হচ্ছে আপনার কম্পিউটারের নতুন কোন ফোল্ডারে `npm init astro` রান করা। আমাদের সিএলআই উইজার্ড আপনাকে একটি নতুন Astro প্রোজেক্ট শুরু করতে সাহায্য করবে।
|
||||
|
||||
মাত্র ৫টি সহজ ও ছোট ধাপে Astro নিয়ে কাজ করা শুরু করতে , আমাদের [কুইকস্টার্ট গাইডটি](quick-start) চেক করুন।
|
||||
|
||||
অথবা, Astro সেটআপ এর উপর সম্পূর্ণ একটি ওয়াকথ্রুর জন্য আমাদের [ইন্সটলেশন গাইডটি](/installation) চেক করুন।
|
||||
|
||||
### অনলাইন প্লেগ্রাউন্ড
|
||||
|
||||
আপনি যদি ব্রাউজারে Astro নিয়ে কাজ করতে চান, তাহলে আপনি একটি অনলাইন কোড প্লেগ্রাউন্ড ব্যবহার করতে পারেন। এজন্য আমাদের [কোডস্যান্ডবক্স](https://codesandbox.io/s/astro-template-hugb3)-এর "Hello World!" টেমপ্লেটটি ব্যবহার করতে পারেন।
|
||||
|
||||
_দ্রষ্টব্য: বর্তমানে কোডস্যান্ডবক্সে কিছু ফিচার (যেমন: ফাস্ট রিফ্রেশ) প্রাথমিক পর্যায়ে রয়েছে।_
|
||||
|
||||
## Astro শিখুন
|
||||
|
||||
বিভিন্ন ব্যাকগ্রাউন্ডের বিভিন্ন ধরণের মানুষ বিভিন্ন পদ্ধতিতে শিখার আগ্রহ নিয়ে Astro-তে আসে। আপনি ব্যবহারিক বা তাত্ত্বিক যে পদ্ধতিতেই শিখতে পছন্দ করেন, আমাদের আশা এই অংশটি আপনাকে সহায়তা করবে।
|
||||
|
||||
- যদি আপনি **করে করে** শিখতে পছন্দ করেন, তাহলে আমাদের [উদাহরণগুলো](https://github.com/snowpackjs/astro/tree/main/examples) দিয়ে শুরু করুন।
|
||||
- আর যদি আপনি **ধাপে ধাপে** বিষয়গুলো বুঝতে চান, তাহলে আমাদের [মৌলিক ধারণা এবং সহায়িকাসমূহ](/core-concepts/project-structure) দেখুন।
|
||||
|
||||
অন্যান্য যেকোনো অপরিচিত প্রযুক্তির মতো, Astro শিখতেও কিছুটা প্রচেষ্টার প্রয়োজন রয়েছে। কিন্তু, আমরা জানি, আপনি লেগে থাকলে অতি দ্রুতই এর সাথে মানিয়ে নিতে _পারবেন_।
|
||||
|
||||
### `.astro` সিনট্যাক্স শিখুন
|
||||
|
||||
আপনি যখন Astro শিখা শুরু করবেন, আপনি অনেকগুলো `.astro` ফাইল খেয়াল করবেন। এটা **Astro-এর কম্পোনেন্ট সিনট্যাক্স**, একটি বিশেষ এইচটিএমএল-এর মতো ফাইল ফরম্যাট যা Astro টেমপ্লেটিং-এর জন্য ব্যবহার করে। এটাকে এইচটিএমএল এবং জেএসএক্স-এর সাথে মিল রেখে তৈরি করা হয়েছে।
|
||||
|
||||
আমাদের [Astro কম্পোনেন্ট](/core-concepts/astro-components)-এর উপর সহায়ক গাইডটি আপনাকে Astro সিনট্যাক্স-এর সাথে পরিচিত করে তুলবে, আর এটিই শিখার সবচেয়ে ভালো উপায়।
|
||||
|
||||
### এপিআই রেফারেন্স
|
||||
|
||||
যদি আপনি কোনো নির্দিষ্ট Astro এপিআই-এর সম্বন্ধে বিস্তারিত জানতে চান তাহলে এই ডকুমেন্টেশনটি আপনাকে সাহায্য করবে। উদাহরণস্বরূপ, [কনফিগারেশন রেফারেন্সে](/reference/configuration-reference) সকল কনফিগারেশন অপশনের তালিকা দেয়া আছে। [বিল্ট-ইন কম্পোনেন্টস রেফারেন্সে](/reference/builtin-components) সকল বিল্ট-ইন কম্পোনেন্টের তালিকা দেয়া আছে, যেমন `<Markdown />` আর `<Prism />`।
|
||||
|
||||
### ভার্সনকৃত ডকুমেন্টেশন
|
||||
|
||||
এই ডকুমেন্টেশনটি সবসময় Astro-এর লেটেস্ট ভার্সনকে প্রতিফলিত করে। যখন আমরা v1.0-এর মাইলফলকটি স্পর্শ করব, তখন আমরা ভার্সনকৃত ডকুমেন্টেশন ফিচারটি সংযোজন করব।
|
||||
|
||||
## অবগত থাকুন
|
||||
|
||||
[@astrodotbuild](https://twitter.com/astrodotbuild) টুইটার অ্যাকাউন্টটি Astro টিম থেকে যেকোনো আপডেট পাওয়ার অফিসিয়াল মাধ্যম।
|
||||
|
||||
আমরা আমাদের [ডিসকর্ড সার্ভারের](https://astro.build/chat) **#announcements** চ্যানেলেও যেকোনো নতুন বিজ্ঞপ্তি প্রকাশ করে থাকি।
|
||||
|
||||
প্রতিটি Astro রিলিজের জন্য আমরা নতুন ব্লগ পোস্ট করি না, কিন্তু আপনি Astro রিপোজিটরির [`CHANGELOG.md`](https://github.com/snowpackjs/astro/blob/main/packages/astro/CHANGELOG.md) ফাইলে প্রতিটি রিলিজের বিস্তারিত পরিবর্তনসূচি দেখতে পারবেন।
|
||||
|
||||
## কিছু অনুপস্থিত মনে হচ্ছে?
|
||||
|
||||
আপনার যদি ডকুমেন্টেশনে কোনো কিছু অনুপস্থিত মনে হয় বা কোনো অংশকে বিভ্রান্তিকর মনে হয়, তাহলে দয়া করে আপনার পরামর্শসহ [একটি ইস্যু ফাইল করুন](https://github.com/snowpackjs/astro/issues/new/choose) অথবা [@astrodotbuild](https://twitter.com/astrodotbuild) টুইটার অ্যাকাউন্টটিতে টুইট করুন। আমরা আপনাদের পরামর্শ শুনতে সর্বদা আগ্রহী!
|
||||
|
||||
## ক্রেডিট
|
||||
|
||||
এই গাইডটি মূলত [React-এর](https://reactjs.org/) **শুরু করুন** গাইডের উপর ভিত্তি করে লিখা হয়েছিল।
|
|
@ -1,101 +0,0 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Routing
|
||||
---
|
||||
|
||||
Astro uses **file-based routing** to generate your build URLs based on the file layout of your project `src/pages` directory. When a file is added to the `src/pages` directory of your project, it is automatically available as a route based on its filename.
|
||||
|
||||
## Static routes
|
||||
|
||||
Astro Components (`.astro`) and Markdown Files (`.md`) in the `src/pages` directory become pages on your website. Each page's route is decided based on its filename and path within the `src/pages` directory. This means that there is no separate "routing config" to maintain in an Astro project.
|
||||
|
||||
```bash
|
||||
# Example: Static routes
|
||||
src/pages/index.astro -> mysite.com/
|
||||
src/pages/about.astro -> mysite.com/about
|
||||
src/pages/about/index.astro -> mysite.com/about
|
||||
src/pages/about/me.astro -> mysite.com/about/me
|
||||
src/pages/posts/1.md -> mysite.com/posts/1
|
||||
```
|
||||
|
||||
## Dynamic routes
|
||||
|
||||
Sometimes, you need to generate many URLs from a single page component. Astro uses file-based routing to support **dynamic route parameters** in the filename, so that one page can match many dynamic routes based on some pattern.
|
||||
|
||||
An important thing to keep in mind: Astro is a static site builder. There is no Astro server to run in production, which means that every page must be built ahead of time. Pages that use dynamic routes must export a `getStaticPaths()` function which will tell Astro exactly what pages to generate. Learn more by viewing the complete [API Reference](/reference/api-reference#getstaticpaths).
|
||||
|
||||
### Named parameters
|
||||
|
||||
Dynamic parameters are encoded into the filename using `[bracket]` notation:
|
||||
|
||||
- `pages/blog/[slug].astro` → `/blog/:slug` (`/blog/hello-world`, `/blog/post-2`, etc.)
|
||||
- `pages/[username]/settings.astro` → (`/fred/settings`, `/drew/settings`, etc.)
|
||||
- `pages/[lang]-[version]/info.astro` → (`/en-v1/info`, `/fr-v2/info`, etc.)
|
||||
|
||||
#### Example: Named parameters
|
||||
|
||||
Consider the following page `pages/post/[pid].astro`:
|
||||
|
||||
```jsx
|
||||
---
|
||||
// Example: src/pages/post/[pid].astro
|
||||
const {pid} = Astro.request.params;
|
||||
---
|
||||
<p>Post: {pid}</p>
|
||||
```
|
||||
|
||||
Any route like `/post/1`, `/post/abc`, etc. will be matched by `pages/post/[pid].astro`. The matched path parameter will be passed to the page component at `Astro.request.params`.
|
||||
|
||||
For example, the route `/post/abc` will have the following `Astro.request.params` object available:
|
||||
|
||||
```json
|
||||
{ "pid": "abc" }
|
||||
```
|
||||
|
||||
Multiple dynamic route segments can be combined to work the same way. The page `pages/post/[pid]/[comment].astro` will match the route `/post/abc/a-comment` and its `query` object will be:
|
||||
|
||||
```json
|
||||
{ "pid": "abc", "comment": "a-comment" }
|
||||
```
|
||||
|
||||
### Rest parameters
|
||||
|
||||
If you need more flexibility in your URL routing, you can use a rest parameter as a universal catch-all. You do this by adding three dots (`...`) inside your brackets. For example:
|
||||
|
||||
- `pages/post/[...slug].astro` → (`/post/a`, `/post/a/b`, `/post/a/b/c`, etc.)
|
||||
|
||||
Matched parameters will be sent as a query parameter (`slug` in the example) to the page. In the example above, the path `/post/a/b/c` will have the following `query` object:
|
||||
|
||||
```json
|
||||
{ "slug": "a/b/c" }
|
||||
```
|
||||
|
||||
You can use names other than `slug`, such as: `[...param]` or `[...name]`.
|
||||
|
||||
Rest parameters are optional by default, so `pages/post/[...slug].astro` could match `/post/` as well.
|
||||
|
||||
#### Example: Rest parameters
|
||||
|
||||
For a real-world example, you might implement GitHub's file viewer like so:
|
||||
|
||||
```
|
||||
/[org]/[repo]/tree/[branch]/[...file]
|
||||
```
|
||||
|
||||
In this example, a request for `/snowpackjs/astro/tree/main/docs/public/favicon.svg` would result in the following parameters being available to the page:
|
||||
|
||||
```js
|
||||
{
|
||||
org: 'snowpackjs',
|
||||
repo: 'astro',
|
||||
branch: 'main',
|
||||
file: 'docs/public/favicon.svg'
|
||||
}
|
||||
```
|
||||
|
||||
## Caveats
|
||||
|
||||
- Static routes without path params will take precedence over all other routes, and named path params over catch all path params. Take a look at the following examples:
|
||||
- `pages/post/create.astro` - Will match `/post/create`
|
||||
- `pages/post/[pid].astro` - Will match `/post/1`, `/post/abc`, etc. But not `/post/create`
|
||||
- `pages/post/[...slug].astro` - Will match `/post/1/2`, `/post/a/b/c`, etc. But not `/post/create`, `/post/abc`
|
|
@ -1,62 +0,0 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Introduktion
|
||||
lang: da
|
||||
---
|
||||
|
||||
Astro er en moderne statisk side bygger. Lær hvad Astro handler om på [vores hjemmeside](https://astro.build/) eller [vores udgivelsesmeddelelser](https://astro.build/blog/introducing-astro). Denne side er et overblik over Astro-dokumentationen og alle relaterede ressourcer.
|
||||
|
||||
Leder du efter et hurtigt overblik over hvad Astro er? [Besøg vores hjemmeside.](https://astro.build)
|
||||
|
||||
## Prøv Astro
|
||||
|
||||
Den nemmeste måde at prøve Astro på er ved at køre `npm init astro` i en ny mappe på din maskine. Vores CLI-guide vil hjælpe dig med at starte et nyt Astro projekt.
|
||||
|
||||
Besøg vores [Hurtigstartsguide](/quick-start) for at komme i gang med Astro i 5 hurtige og nemme trin.
|
||||
|
||||
Alternativt kan du læse vores [Installationsguide](/installation) for en fuld gennemgang af hvordan du sætter Astro op.
|
||||
|
||||
### Online Legepladser
|
||||
|
||||
Hvis du er interesseret i at lege med Astro i browseren, kan du bruge en online kodelegeplads. Prøv vores "Hello World!" skabelon på [CodeSandbox](https://codesandbox.io/s/astro-template-hugb3).
|
||||
|
||||
_Bemærk: Nogle funktioner (f.eks. Hurtig opdatering) er i øjeblikket begrænset på CodeSandbox._
|
||||
|
||||
## Lær Astro
|
||||
|
||||
Alle slags mennesker kommer til Astro fra forskellige baggrunde og medbringer forskellige læringsstile. Uanset om du foretrækker en mere teoretisk eller praktisk tilgang, håber vi at du finder dette afsnit nyttigt.
|
||||
|
||||
- Hvis du foretrækker at **lære ved at gøre**, kan du starte med vores [liste af eksempler](https://github.com/snowpackjs/astro/tree/main/examples).
|
||||
- Hvis du foretrækker at **lære koncepter trin for trin**, kan du starte med vores [grundlæggende koncepter og vejledninger](/core-concepts/project-structure).
|
||||
|
||||
Som enhver anden ukendt teknologi har Astro en lille indlæringskurve. Men med øvelse og lidt tålmodighed, ved vi at du _vil_ få styr på det på ingen tid.
|
||||
|
||||
### Lær `.astro` Syntaks
|
||||
|
||||
Når du begynder at lære Astro, vil du se mange filer med filtypen `.astro`. Dette er **Astros Komponent Syntaks**: et specielt HTML-lignende filformat som Astro bruger til templating. Det er designet til at føles bekendt for alle med HTML- eller JSX-erfaring
|
||||
|
||||
Vores nyttige guide om [Astro-komponenter](/core-concepts/astro-components) introducerer dig til Astro-syntaksen, og er den bedste måde at lære på.
|
||||
|
||||
### API Reference
|
||||
|
||||
Dette dokumentationsafsnit er nyttigt når du vil lære flere detaljer om en bestemt Astro API. F.eks. indeholder [Konfigurationsreference](/reference/configuration-reference) en liste over alle tilgængelige konfigurationsmuligheder. [Indbyggede komponenter-reference](/reference/builtin-components) indeholder en liste over alle tilgængelige kernekomponenter, såsom `<Markdown />` og `<Prism />`.
|
||||
|
||||
### Versioneret dokumentation
|
||||
|
||||
Denne dokumentation afspejler altid den seneste stabile version af Astro. Når vi når v1.0-milepælen, vil vi tilføje muligheden for at se versioneret dokumentation.
|
||||
|
||||
## Hold dig orienteret
|
||||
|
||||
Twitter-kontoen [@astrodotbuild](https://twitter.com/astrodotbuild) er den officielle kilde til opdateringer fra Astro-teamet.
|
||||
|
||||
Vi sender også udgivelsesmeddelelser til vores [Discord-fællesskab](https://astro.build/chat) i #announcements kanalen.
|
||||
|
||||
Ikke hver Astro udgivelse fortjener sit eget blogindlæg, men du kan finde en detaljeret ændringsliste for hver udgivelse i [`CHANGELOG.md` filen i Astro-repositoriet](https://github.com/snowpackjs/astro/blob/main/packages/astro/CHANGELOG.md).
|
||||
|
||||
## Mangler der noget?
|
||||
|
||||
Hvis der mangler noget i dokumentationen, eller hvis du synes, at en del er forvirrende, skal du [indsende et Issue om dokumentationen](https://github.com/snowpackjs/astro/issues/new/choose) med dit forslag til forbedringer, eller tweet på [@astrodotbuild](https://twitter.com/astrodotbuild) Twitter-kontoen. Vi elsker at høre fra dig!
|
||||
|
||||
## Kredit
|
||||
|
||||
Denne startvejledning var oprindeligt baseret på [React's](https://reactjs.org/) startvejledning.
|
|
@ -1,69 +0,0 @@
|
|||
---
|
||||
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 erst einmal einen kurzen Überblicke erhalten, 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 dabei, ein neues Astro-Projekt aufzusetzen.
|
||||
|
||||
Um mit Astro in fünf 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 erst einmal mit Astro in Deinem Browser herumspielen willst, kannst Du einen Online-Code-Spielplatz benutzen. Probiere 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 anderen Lernweisen zu Astro. Unabhängig davon, ob Du lieber theoretisch oder praktisch lernst, hoffen wir, dass Dir dieser Abschnitt weiterhilft.
|
||||
|
||||
- Falls Du lieber **praktisch lernst**, suche Dir ein Beispiel aus unserer [Beispiel Liste](https://github.com/snowpackjs/astro/tree/main/examples) aus und fange direkt an.
|
||||
|
||||
- Falls Du lieber **theoretisch lernst**, kannst Du mit unseren [grundlegenden Konzepten und Anleitungen](/core-concepts/project-structure) beginnen.
|
||||
|
||||
Wie alle unbekannten Technologien, hat auch Astro eine 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 Dateiendung `.astro` 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 [Konfigurationsdokumentation](/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 `<Markdown />` und `<Code />`.
|
||||
|
||||
### Versionierte Dokumentation
|
||||
|
||||
Diese Dokumentation ist immer auf dem Stand der letzten _stable_ Version von Astro. Sobald wir den Meilenstein der Version v1.0 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 einen 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/).
|
|
@ -1,62 +0,0 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Bien démarrer
|
||||
lang: fr
|
||||
---
|
||||
|
||||
Astro est un générateur de site statique moderne. Comprenez ce qu'est Astro en visitant [notre page d'accueil](https://astro.build/) ou [notre annonce de sortie](https://astro.build/blog/introducing-astro). Cette page est une vue d'ensemble de la documentation d'Astro et de toutes les ressources associées.
|
||||
|
||||
Vous cherchez un rapide condensé de ce qu'offre Astro ? [Visitez notre page d'accueil.](https://astro.build)
|
||||
|
||||
## Essayer Astro
|
||||
|
||||
La manière la plus simple d'essayer Astro est de lancer `npm init astro` à partir d'un nouveau dossier depuis votre machine. Notre utilitaire CLI vous assistera dans la création d'un nouveau projet Astro.
|
||||
|
||||
Pour bien débuter avec Astro en 5 étapes rapides et faciles, visitez notre [Guide de démarrage rapide](quick-start).
|
||||
|
||||
Autrement, lisez notre [Guide d'installation](/installation) pour un accompagnement pas-à-pas sur la mise en place d'Astro.
|
||||
|
||||
### Terrains de jeu en ligne (Online Playground)
|
||||
|
||||
Si vous voulez tester Astro directement dans votre navigateur, vous pouvez utiliser un playground en ligne. Essayez notre modèle "Hello World!" sur [CodeSandbox](https://codesandbox.io/s/astro-template-hugb3).
|
||||
|
||||
_Note: quelques-unes des fonctionnalités (ex : Rafraîchissement Rapide) sont pour le moment limitées sur CodeSandbox._
|
||||
|
||||
## Apprendre Astro
|
||||
|
||||
Tous les développeurs qui essaient Astro n'ont ni la même expérience, ni les mêmes méthodes d'apprentissage. Que vous préfériez une approche plutôt théorique ou pratique, nous espérons que vous trouverez l'aide qu'il vous faut dans cette section.
|
||||
|
||||
- Si vous préférez une **approche pratique**, commencez avec notre [librairie d'exemples](https://github.com/snowpackjs/astro/tree/main/examples).
|
||||
- Si vous préférez **apprendre les concepts étape par étape**, commencez avec nos [fondamentaux et guides](/core-concepts/project-structure).
|
||||
|
||||
Comme toute nouvelle technologie, Astro possède une certaine courbe d'apprentissage. Malgré cela, avec de la pratique et de la patience, nous savons, que _vous_ allez prendre la main, en très peu de temps.
|
||||
|
||||
### Apprendre la syntaxe `.astro`
|
||||
|
||||
Quand vous débutez l'apprentissage d'Astro, vous allez rencontrer beaucoup de fichier avec l'extension `.astro`. C'est la **Syntaxe des Composants Astro** : des fichiers particuliers avec un format similaire au HTML qu'Astro utilise comme template. Ils ont été conçus pour être familiers à toute personne ayant une expérience avec le HTML ou le JSX.
|
||||
|
||||
Notre guide sur les [composants Astro](/core-concepts/astro-components) vous présente la syntaxe Astro et reste la meilleure façon d'apprendre.
|
||||
|
||||
### Documentation de l'API
|
||||
|
||||
Cette documentation vous sera utile si vous souhaitez comprendre en détails certaines API d'Astro. Par exemple, la [Documentation de la Configuration](/reference/configuration-reference) liste toutes les options de configuration à votre disposition. La [Documentation des Composants de base](/reference/builtin-components) liste tous les composants disponibles de base, comme `<Markdown />` et `<Code />`.
|
||||
|
||||
### Documentation versionnée
|
||||
|
||||
Cette documentation reflète toujours la dernière version stable d'Astro. Dès que nous auront atteint l'étape de la v1.0, nous ajouterons la possibilité de parcourir la documentation versionnée.
|
||||
|
||||
## Rester informé
|
||||
|
||||
Le compte Twitter [@astrodotbuild](https://twitter.com/astrodotbuild) est la source officielle d'information de l'équipe Astro.
|
||||
|
||||
Nous publions également les annonces de nouvelles versions sur notre [Communauté Discord](https://astro.build/chat) dans le salon #announcements.
|
||||
|
||||
Toutes les releases d'Astro ne requièrent pas leur propre article de blog, mais vous pouvez trouver un changelog détaillé de toutes les releases dans le [fichier `CHANGELOG.md` du dépôt Astro](https://github.com/snowpackjs/astro/blob/main/packages/astro/CHANGELOG.md).
|
||||
|
||||
## Quelque chose vous manque ?
|
||||
|
||||
Si vous pensez que quelque chose manque dans la documentation ou si vous en trouvez une partie déroutante, veuillez [créer une "issue" sur le dépôt de la documentation](https://github.com/snowpackjs/astro/issues/new/choose) avec vos suggestions d'amélioration, ou bien mentionnez le compte [@astrodotbuild](https://twitter.com/astrodotbuild) sur Twitter. Nous adorons avoir de vos nouvelles !
|
||||
|
||||
## Crédits
|
||||
|
||||
Ce guide de démarrage est basé sur le guide "Bien débuter" de [React](https://reactjs.org/).
|
|
@ -1,160 +0,0 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Installation
|
||||
lang: fr
|
||||
---
|
||||
|
||||
Il y a plusieurs façons d'installer Astro dans un nouveau projet.
|
||||
|
||||
## Prérequis
|
||||
|
||||
- **Node.js** - `v12.20.0`, `v14.13.1`, `v16.0.0`, or plus.
|
||||
- **Éditeur de texte** - Privilégiez [VS Code](https://code.visualstudio.com/) et [l'extension Astro officielle](https://marketplace.visualstudio.com/items?itemName=astro-build.astro-vscode).
|
||||
- **Terminal** - Astro s'utilise principalement en ligne de commande.
|
||||
|
||||
Ce guide utilise [`npm`](https://www.npmjs.com/) dans les exemples ci-après, mais vous pouvez utiliser [`yarn`](https://yarnpkg.com/) ou [`pnpm`](https://pnpm.io/) si vous y êtes habitué·e.
|
||||
|
||||
## Initialisation complète
|
||||
|
||||
`npm init astro` est le moyen le plus facile de créer un nouveau projet avec Astro. Entrez cette commande dans un terminal pour lancer `create-astro`, l'assistant d'installation.
|
||||
|
||||
```bash
|
||||
# Avec NPM
|
||||
npm init astro
|
||||
|
||||
# Yarn
|
||||
yarn create astro
|
||||
```
|
||||
|
||||
L'assistant d'installation [`create-astro`](https://github.com/snowpackjs/astro/tree/main/packages/create-astro) vous propose de choisir entre différents [squelettes d'application](/examples), mais offre aussi la possibilité d'importer un projet Astro directement depuis GitHub.
|
||||
|
||||
```bash
|
||||
# Note : remplacez "my-astro-project" avec le nom de votre projet.
|
||||
|
||||
# npm 6.x
|
||||
npm init astro my-astro-project --template starter
|
||||
# npm 7+ (tiret -- supplémentaire)
|
||||
npm init astro my-astro-project -- --template starter
|
||||
# yarn
|
||||
yarn create astro my-astro-project --template starter
|
||||
# À partir d'un template disponible sur GitHub
|
||||
npm init astro my-astro-project -- --template [GITHUB_USER]/[REPO_NAME]
|
||||
# ... ou si ce template ce trouve à l'intérieur d'un dépôt GitHub
|
||||
npm init astro my-astro-project -- --template [GITHUB_USER]/[REPO_NAME]/path/to/template
|
||||
```
|
||||
|
||||
Après que `create-astro` a mis en place l'architecture de votre projet, n'oubliez pas d'installer les dépendances avec npm, yarn ou pnpm. Par exemple avec npm:
|
||||
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
Vous pouvez maintenant [lancer](#démarrer-astro) votre projet. Une fois votre projet prêt à être déployé, vous pourrez [le compiler](#compiler-avec-astro). Astro va empaqueter votre application et produire les fichiers statiques nécessaires pour que vous puissiez [déployer](/guides/deploy) votre application.
|
||||
|
||||
## Installation manuelle
|
||||
|
||||
Vous pouvez installer Astro en vous passant de l'assistant `create-astro` avec les quelques étapes suivantes.
|
||||
|
||||
### Créer un projet
|
||||
|
||||
```bash
|
||||
# Créez et placez vous dans un nouveau dossier
|
||||
mkdir my-astro-project
|
||||
cd my-astro-project
|
||||
```
|
||||
|
||||
### Créer un `package.json`
|
||||
|
||||
```bash
|
||||
# Cette commande va créer un fichier package.json basique
|
||||
npm init --yes
|
||||
```
|
||||
|
||||
Astro est conçu pour fonctionner avec tout l'ecosystème npm. Cela est rendu possible par un fichier de projet nommé `package.json` à la racine de votre projet. Si vous n'êtes pas familier·e avec le fichier `package.json`, nous vous recommandons fortement de lire [la documentation officielle sur le site de npm](https://docs.npmjs.com/creating-a-package-json-file).
|
||||
|
||||
### Installer Astro
|
||||
|
||||
En suivant les instructions précédentes, vous devriez avoir un dossier avec un seul fichier `package.json` dedans. Vous pouvez maintenant ajouter Astro à votre projet.
|
||||
|
||||
```bash
|
||||
npm install astro
|
||||
```
|
||||
|
||||
Vous pouvez aussi remplacer la section "scripts" du fichier `package.json` avec les lignes suivantes :
|
||||
|
||||
```diff
|
||||
"scripts": {
|
||||
- "test": "echo \"Error: no test specified\" && exit 1"
|
||||
+ "dev": "astro dev",
|
||||
+ "build": "astro build",
|
||||
+ "preview": "astro preview"
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
La commande [`dev`](#start-astro) démarre le serveur de développement Astro à l'adresse `http://localhost:3000`. Une fois votre projet terminé, la commande [`build`](#build-astro) produit votre site dans le dossier `dist/`. [En savoir plus sur le déploiement d'un site développé avec Astro.](/guides/deploy)
|
||||
|
||||
### Créer une première page
|
||||
|
||||
Ouvrez votre éditeur favori, et créez un nouveau fichier :
|
||||
|
||||
1. Créez un nouveau fichier à l'emplacement `src/pages/index.astro`.
|
||||
2. Copiez-collez l'extrait suivant (`---` compris) dedans.
|
||||
|
||||
```astro
|
||||
---
|
||||
// Le code JS/TS écrit entre les (---) n'est exécuté que par le serveur
|
||||
console.log('Coucou dans le terminal')
|
||||
---
|
||||
|
||||
<html>
|
||||
<body>
|
||||
<h1>Hello, World!</h1>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
<style lang="scss">
|
||||
body {
|
||||
h1 {
|
||||
color: orange;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<script>
|
||||
// Le code JS écrit ici n'est exécuté que dans le navigateur
|
||||
console.log('Coucou dans la console du navigateur')
|
||||
</script>
|
||||
```
|
||||
|
||||
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).
|
|
@ -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).
|
|
@ -1,5 +1,5 @@
|
|||
---
|
||||
import SplashLayout from '../layouts/SplashLayout.astro';
|
||||
import SplashLayout from '../../layouts/SplashLayout.astro';
|
||||
---
|
||||
|
||||
<SplashLayout title="Not Found">
|
241
docs/src/pages/group-1/blog/island-architecture.md
Normal file
241
docs/src/pages/group-1/blog/island-architecture.md
Normal file
|
@ -0,0 +1,241 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Island Architecture
|
||||
draft: true
|
||||
---
|
||||
|
||||
<!--
|
||||
@aFuzzyBear: I have been spending most the day learning more about Island Architecture, wrote plenty of notes, listened to Fred K Schott's interview on Speakeasy(https://www.youtube.com/watch?v=mgkwZqVkrwo) and the interview with Jason Lengstrof (https://www.youtube.com/watch?v=z15YLsLMtu4)
|
||||
Figured I might give writing this a wee go,
|
||||
|
||||
I wanted to take this from the direction of it being more of a critique of the past and present state of affairs in web dev
|
||||
Post structure:
|
||||
1)Start with an introduction to Islands Arch
|
||||
2)Talk about the different Architectures that can be used in Web-dev
|
||||
3)MVC/StaticSites - SPA's
|
||||
4)Frameworks, get some external links onto the page
|
||||
4)Moving to ESM
|
||||
5)Benefits of ESM
|
||||
6)
|
||||
|
||||
-->
|
||||
|
||||
<!-- Intro -->
|
||||
|
||||
> "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](<https://en.wikipedia.org/wiki/Hydration_(web_development)>) 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 `<script>` within our HTML document.
|
||||
|
||||
This means for our page, we need to wait for React to be fetched and downloaded, then parsed and executed, have it wait for the page to display the carousel before we receive the behaviour and functionality we expect from our small dynamic component.
|
||||
|
||||
Instead of this laborious process, one would simply render the carousel in HTML on the server and have a dedicated `<script>` that is emitted when the component for the carousel is displayed.
|
||||
|
||||
This would then load the functionality for the carousel in-place, transforming it instantly into a dynamic image slide show, with navigation.
|
||||
|
||||
## Island Hydration
|
||||
|
||||
By now the idea of Island-architecture must be settling in, and one must be thinking, this is just [Progressive Hydration](<https://en.wikipedia.org/wiki/Hydration_(web_development)#Progressive_rehydration>), and you wouldn't be overly off mark.
|
||||
|
||||
Progressive Hydration that is used in frameworks like: Angular, React, Preact, Vue. Are individual components, which are loaded and then initialised over a period of time.
|
||||
|
||||
Using scheduling processes, and accounting for things like viewport visibility, content value, probability of interaction etc. They can abstract away the intricacies and delivery this form of hydration for developers.
|
||||
|
||||
By using Island styled components, this form of hydration essentially comes for **free**.
|
||||
|
||||
Since the larger dynamic components on a page are being initialised separately, not progressively. The difference lets individual regions on the page to become interactive without the page requiring to first load anything.
|
||||
|
||||
This expands further, as it doesn't need any form of ['Top-down Rendering'](https://developers.google.com/web/fundamentals/performance/rendering).
|
||||
|
||||
Since there is no outer `<div id='root'>` element that needs to be initialised before the inner contents can be exposed.
|
||||
|
||||
Every region of the page is an isolated unit, an island, on its own, connected to others by the HTML page. With such an approach the benefits do begin to stack up.
|
||||
|
||||
A key benefit is seen with the site performance. Since isolation is inherent, if a single issue affects a component, it wouldn't affect the other _islands_ on the page.
|
||||
|
||||
## Exploring the Island
|
||||
|
||||
As we explore further into the Island, we can see immediate trade differences between framework produced SSR solutions and those that could be provided by using Island Architecture.
|
||||
|
||||
Quickly wandering back to the Status Quo for a brief interlude. We use SSR with SPA's to help tackle the downside of SPA's and its SEO. Appealing to the search engines in this manner has another negative effect on the UX.
|
||||
|
||||
> "...visitors are left waiting for the actual functionality of a page to arrive while staring at a frustratingly fake version of that page." - Jason Miller
|
||||
|
||||
There are other issues that stem from traditional SSR, and being idly unawares of such performance pitfalls, gives rise to an orchestra of potential problems.
|
||||
|
||||
Further compounded with misconceptions on implementations and utilisations of solid SSR techniques, this practice is increasingly prominent amongst the Status Quoticians.
|
||||
|
||||
The one most obvious drawback with SSR is the amount of work JS has to do during the initial page load, is far excessive than is necessary, and is extremely inefficient use of resources.
|
||||
|
||||
We find with our "Islands" model, that with Server rendering is a fundamental part of how pages are delivered to the browser.
|
||||
|
||||
The responded HTML, would still contain all the rendered content that the user requested. With some islands yet to engage their client-sided interactivity. The document sent should contain all the content that the User would need.
|
||||
|
||||
An example of this would be a product page for a e-commerce business. A product page, using the Islands model would contain that product's description, price etc, Having the dynamic components becoming interactive on demand.
|
||||
|
||||
We also discover that with the Islands model we have better accessibility and discoverability of our elements and the contents within.
|
||||
|
||||
Less code is eventually shipped from each island which is a massive cost-saving benefit.
|
||||
|
||||
However the conceptual idea of using Islands from a Web developers viewpoint is that, we get to come full circle and begin to deliver lightening fast user experiences without having the previous trade-offs and penalties that came from previous design models.
|
||||
|
||||
They're plenty of more important discoveries yet to be made when exploring the Island Architecture model in more detail.
|
||||
|
||||
Jason finished his post with the following:
|
||||
|
||||
> "It's possible...that adopting a model like this requires more up-front design thinking. There are far few batteries-included options available ...Who knows, maybe we can fix that." - August 2020
|
||||
|
||||
## Astrolands
|
||||
|
||||
<!-- Conclusion, final words. Here tie in Astro -->
|
||||
|
||||
Here at Astro, we fully embrace the principles ideas behind Jason's 'Island Architecture'. As a result, we have been hard at work trying to apply this new innovative concept into Web Development and the JS ecosystem.
|
||||
|
||||
We would like to take this time to encourage you to start exploring how Astro accomplishes this. And experience how easy it is to adopt as an architectural design philosophy.
|
|
@ -23,36 +23,22 @@ Docusaurus was designed to build documentation websites and has some built-in, d
|
|||
|
||||
In most cases, Astro websites will load significantly faster than Docusaurus websites. This is because Astro automatically strips unnecessary JavaScript from the page, hydrating only the individual components that need it. This feature is called [partial hydration](/core-concepts/component-hydration).
|
||||
|
||||
Docusaurus doesn't support partial hydration, and instead makes the user load and rehydrate the entire page in the browser, even if most of the page content is static. This creates a slower page load and worse performance for your website. There is no way to disable this behavior in Docusaurus.
|
||||
Docusaurus doesn't support partial hydration, and instead has the user load and rehydrate the entire page in the browser, even if most of the page content is static. This creates a slower page load and worse performance for your website. There is no way to disable this behavior in Docusaurus.
|
||||
|
||||
#### Case Study: Building a Documentation Website
|
||||
|
||||
[docusaurus.io/docs](https://docusaurus.io/docs) is the official Docusaurus documentation website, built with Docusaurus. The website offers a similar enough design and featureset to compare against the official Astro documentation website. This gives us a **_rough, real-world_** comparison between the two site builders.
|
||||
|
||||
- **Docusaurus performance score**: 26 out of 100 [(full audit)](https://lighthouse-dot-webdotdevsite.appspot.com//lh/html?url=https%3A%2F%2Fdocusaurus.io%2Fdocs)
|
||||
- **Astro performance score**: 99 out of 100 [(full audit)](https://lighthouse-dot-webdotdevsite.appspot.com//lh/html?url=https%3A%2F%2Fdocs.astro.build%2Fgetting-started)
|
||||
- **Astro performance score**: 95 out of 100 [(full audit)](https://lighthouse-dot-webdotdevsite.appspot.com//lh/html?url=https%3A%2F%2Fdocs.astro.build%2Fgetting-started)
|
||||
|
||||
One big reason behind this performance difference is Astro's smaller JavaScript payload: [docusaurus.io/docs](https://docusaurus.io/docs) loads **238kb** of JavaScript on first page load while [docs.astro.build](https://docs.astro.build) loads **78.7kb** (67% less JavaScript, overall) _after_ first load.
|
||||
|
||||
## Elder.js vs. Astro
|
||||
|
||||
[Elder.js](https://elderguide.com/tech/elderjs/) is an opinionated static site builder built for Svelte.
|
||||
|
||||
Elder.js uses Svelte to render your website. Astro is more flexible: you are free to build UI with any popular component library (React, Preact, Vue, Svelte, Solid and others) or Astro's HTML-like component syntax which is similar to HTML + JSX.
|
||||
|
||||
Elder.js is unique on this list as the only other site builder to support [partial hydration](/core-concepts/component-hydration). Both Astro and Elder.js automatically strip unnecessary JavaScript from the page, hydrating only the individual components that need it. Elder's API for partial hydration is a bit different and Astro supports a few features that Elder.js doesn't (like `client:media`). However performance-wise, both projects will build very similar sites.
|
||||
|
||||
Elder.js uses a custom routing solution that may feel unfamiliar to new developers. Astro uses [file-based routing](/core-concepts/routing) which should feel familiar to anyone coming from Next.js, SvelteKit, and even other static site builders like Eleventy.
|
||||
|
||||
Elder.js was designed to run on large websites, and claims to build one website of ~20k pages in less than 10 minutes (on a modest VM). At the time of writing, Astro builds ~1k pages in 66 seconds but has not yet been tested on 20k+ page projects. Astro is still in early beta, and matching Elder.js build speed is a goal for Astro v1.0.
|
||||
|
||||
Elder.js supports both Static Site Generation (SSG) and Server-Side Rendering (SSR). Today, Astro only supports Static Site Generation (SSG).
|
||||
One big reason behind this performance difference is Astro's smaller JavaScript payload: [docusaurus.io/docs](https://docusaurus.io/docs) loads **238kb** of JavaScript on first load while [docs.astro.build](https://docs.astro.build) only loads **9.3kb** (96% less JavaScript, overall).
|
||||
|
||||
## Eleventy vs. Astro
|
||||
|
||||
[Eleventy](https://www.11ty.dev/) is a popular static site builder, powered by Node.js.
|
||||
|
||||
Eleventy uses several [older HTML templating languages](https://www.11ty.dev/docs/languages/) to render your website: Nunjucks, Liquid, Pug, EJS, and others. Astro lets you create pages using your favorite UI component libraries (React, Preact, Vue, Svelte, and others) or a built-in component syntax which is similar to HTML + JSX. Eleventy does not support using modern UI components for HTML templating.
|
||||
Eleventy uses several [older HTML templating languages](https://www.11ty.dev/docs/languages/) to render your website: Nunjucks, Liquid, Pug, EJS, and others. Astro lets you create pages using your favorite UI component libraries (React, Preact, Vue, Svelte, and others) or a built-in component syntax that is similar to HTML/JSX. Eleventy does not support using modern UI components for HTML templating.
|
||||
|
||||
#### Comparing Eleventy vs. Astro Performance
|
||||
|
||||
|
@ -62,38 +48,23 @@ Eleventy achieves this by pushing you to avoid JavaScript entirely. Eleventy sit
|
|||
|
||||
By contrast, Astro automatically builds your client-side JavaScript & CSS for you. Astro automatically strips unnecessary JavaScript from the page, hydrating only the individual components that need it. This feature is called [partial hydration](/core-concepts/component-hydration). While it is possible to achieve this yourself in Eleventy, Astro offers it built in by default.
|
||||
|
||||
<!--
|
||||
## Gatsby vs. Astro
|
||||
|
||||
[Gatsby](https://www.gatsbyjs.com/) is a popular website & application framework for React.
|
||||
**Next.js** is a popular website & application framework for React.
|
||||
|
||||
Gatsby uses React to render your website. Astro is more flexible: you are free to build UI with any popular component library (React, Preact, Vue, Svelte, Solid and others) or Astro's HTML-like component syntax which is similar to HTML + JSX.
|
||||
|
||||
Today, both Gatsby and Astro support Static Site Generation (SSG) only. Gatsby has support for incremental rebuilds, while Astro only supports full site rebuilds. Astro has stated plans to support Server-Side Rendering (SSR) in a future release, while Gatsby has no plans to support SSR.
|
||||
## Hexo vs. Astro
|
||||
|
||||
Gatsby requires a custom GraphQL API for working with all of your site content. While some developers enjoy this model, a common criticism of Gatsby is that this model becomes too complex and difficult to maintain over time, especially as sites grow. Astro has no GraphQL requirement, and instead provides familiar APIs (like `fetch()` and top-level `await`) for data loading close to where the data is needed.
|
||||
**Hexo** is a popular static site generator, powered by Node.js.
|
||||
|
||||
#### Comparing Gastby vs. Astro Performance
|
||||
|
||||
In most cases, Astro websites will load significantly faster than Gatsby websites. This is because Astro automatically strips unnecessary JavaScript from the page, hydrating only the individual components that need it. This feature is called [partial hydration](/core-concepts/component-hydration).
|
||||
|
||||
Gatsby doesn't support partial hydration, and instead makes the user load and rehydrate the entire page in the browser, even if most of the page content is static. This creates a slower page load and worse performance for your website. Gatsby has [a community plugin](https://www.gatsbyjs.com/plugins/gatsby-plugin-no-javascript/) for removing all JavaScript from the page, but this would break many websites. This leaves you with an all-or-nothing decision for interactivity on each page.
|
||||
|
||||
Gatsby has a great plugin ecosystem, which could make Gatsby a better choice for your project depending on your needs. [gatsby-plugin-image](https://www.gatsbyjs.com/plugins/gatsby-plugin-image/) is a popular plugin for image optimizations, which could make Gatsby a better choice for some image-heavy websites.
|
||||
|
||||
#### Case Study: Building a Documentation Website
|
||||
|
||||
[gatsbyjs.com/docs](https://www.gatsbyjs.com/docs/quick-start/) is the official Gatsby documentation website, built with Gatsby. The website offers a similar enough design and feature-set to compare against the official Astro documentation website. This gives us a **_rough, real-world_** comparison between the two site builders for this common use-case.
|
||||
|
||||
- **Gatsby performance score**: 64 out of 100 [(full audit)](https://lighthouse-dot-webdotdevsite.appspot.com//lh/html?url=https%3A%2F%2Fwww.gatsbyjs.com%2Fdocs%2Fquick-start%2F)
|
||||
- **Astro performance score**: 99 out of 100 [(full audit)](https://lighthouse-dot-webdotdevsite.appspot.com//lh/html?url=https%3A%2F%2Fdocs.astro.build%2Fgetting-started)
|
||||
|
||||
One big reason behind this performance difference is Astro's smaller JavaScript payload: [gatsbyjs.com/docs](https://www.gatsbyjs.com/docs/quick-start/) loads **417kb** of JavaScript on first page load while [docs.astro.build](https://docs.astro.build) loads **78.7kb** (81% less JavaScript, overall) _after_ first load.
|
||||
-->
|
||||
|
||||
## Hugo vs. Astro
|
||||
|
||||
[Hugo](https://gohugo.io/) is a popular static site generator, powered by Go.
|
||||
|
||||
Hugo uses a custom [templating language](https://gohugo.io/templates/introduction/) to render your website. Astro lets you create pages using your favorite UI component libraries (React, Preact, Vue, Svelte, and others) or a built-in component syntax which is similar to HTML + JSX. Hugo does not support using modern UI components for HTML templating.
|
||||
Hugo uses a custom [templating language](https://gohugo.io/templates/introduction/) to render your website. Astro lets you create pages using your favorite UI component libraries (React, Preact, Vue, Svelte, and others) or a built-in component syntax that is similar to HTML/JSX. Hugo does not support using modern UI components for HTML templating.
|
||||
|
||||
#### Comparing Hugo vs. Astro Performance
|
||||
|
||||
|
@ -105,7 +76,7 @@ Both Hugo and Astro offer built-in support for building, bundling and minifying
|
|||
|
||||
[Jekyll](https://jekyllrb.com/) is a popular static site generator, powered by Ruby.
|
||||
|
||||
Jekyll uses an older [templating language](https://jekyllrb.com/docs/liquid/) to render your website called Liquid. Astro lets you create pages using your favorite UI component libraries (React, Preact, Vue, Svelte, and others) or a built-in component syntax which is similar to HTML + JSX. Jekyll does not support using modern UI components for HTML templating.
|
||||
Jekyll uses an older [templating language](https://jekyllrb.com/docs/liquid/) to render your website called Liquid. Astro lets you create pages using your favorite UI component libraries (React, Preact, Vue, Svelte, and others) or a built-in component syntax that is similar to HTML/JSX. Jekyll does not support using modern UI components for HTML templating.
|
||||
|
||||
#### Comparing Jekyll vs. Astro Performance
|
||||
|
||||
|
@ -119,7 +90,7 @@ By contrast, Astro automatically builds your client-side JavaScript for you. Ast
|
|||
|
||||
[SvelteKit](https://kit.svelte.dev/) is a popular website & application framework for Svelte.
|
||||
|
||||
SvelteKit uses Svelte to render your website. Astro is more flexible: you are free to build UI with any popular component library (React, Preact, Vue, Svelte, Solid and others) or Astro's HTML-like component syntax which is similar to HTML + JSX.
|
||||
SvelteKit uses Svelte to render your website. Astro is more flexible: you can use any UI component libraries (React, Preact, Vue, Svelte, and others) or Astro's built-in component syntax that is similar to HTML/JSX.
|
||||
|
||||
Both SvelteKit and Astro are frameworks for building websites. SvelteKit does best with highly dynamic websites (like dashboards and inboxes) while Astro does best with highly static websites (like content and eCommerce websites).
|
||||
|
||||
|
@ -129,7 +100,7 @@ SvelteKit supports both Static Site Generation (SSG) and Server-Side Rendering (
|
|||
|
||||
In most cases, Astro websites will load faster than SvelteKit websites. This is because Astro automatically strips unnecessary JavaScript from the page, hydrating only the individual components that need it. This feature is called [partial hydration](/core-concepts/component-hydration).
|
||||
|
||||
SvelteKit doesn't support partial hydration, and instead makes the user load and rehydrate the entire page in the browser, even if most of the page content is static. This creates a slower page load and worse performance for your website. SvelteKit does offer support for [page-level static, zero-JavaScript pages](https://kit.svelte.dev/docs#ssr-and-javascript-hydrate). However, there is no planned support for hydrating individual components on the page. This leaves you with an all-or-nothing decision for interactivity on each page.
|
||||
SvelteKit doesn't support partial hydration, and instead has the user load and rehydrate the entire page in the browser, even if most of the page content is static. This creates a slower page load and worse performance for your website. SvelteKit does offer support for [page-level static, zero-JavaScript pages](https://kit.svelte.dev/docs#ssr-and-javascript-hydrate). However, there is no planned support for hydrating individual components on the page. This leaves you with an all-or-nothing decision for interactivity on each page.
|
||||
|
||||
#### Case Study: Building a Documentation Website
|
||||
|
||||
|
@ -138,7 +109,7 @@ SvelteKit doesn't support partial hydration, and instead makes the user load and
|
|||
One notable difference between the two sites being tested: SvelteKit's documentation is served as a single page while Astro's is broken up into multiple pages. This larger content payload should have a slight negative impact on performance that is not related to the tool itself.
|
||||
|
||||
- **SvelteKit performance score**: 92 out of 100 [(full audit)](https://lighthouse-dot-webdotdevsite.appspot.com//lh/html?url=https%3A%2F%2Fkit.svelte.dev%2Fdocs)
|
||||
- **Astro performance score**: 99 out of 100 [(full audit)](https://lighthouse-dot-webdotdevsite.appspot.com//lh/html?url=https%3A%2F%2Fdocs.astro.build%2Fgetting-started)
|
||||
- **Astro performance score**: 95 out of 100 [(full audit)](https://lighthouse-dot-webdotdevsite.appspot.com//lh/html?url=https%3A%2F%2Fdocs.astro.build%2Fgetting-started)
|
||||
|
||||
SvelteKit performed comparably to Astro in this test.
|
||||
|
||||
|
@ -146,7 +117,7 @@ SvelteKit performed comparably to Astro in this test.
|
|||
|
||||
[Next.js](https://nextjs.org/) is a popular website & application framework for React.
|
||||
|
||||
Next.js uses React to render your website. Astro is more flexible: you are free to build UI with any popular component library (React, Preact, Vue, Svelte, Solid and others) or Astro's HTML-like component syntax which is similar to HTML + JSX.
|
||||
Next.js uses React to render your website. Astro is more flexible: you can use any UI component libraries (React, Preact, Vue, Svelte, and others) or Astro's built-in component syntax that is similar to HTML/JSX.
|
||||
|
||||
Both Next.js and Astro are frameworks for building websites. Next.js does best with highly dynamic websites (like dashboards and inboxes) while Astro does best with highly static websites (like content and eCommerce websites).
|
||||
|
||||
|
@ -156,7 +127,7 @@ Next.js supports both Static Site Generation (SSG) and Server-Side Rendering (SS
|
|||
|
||||
In most cases, Astro websites will load significantly faster than Next.js websites. This is because Astro automatically strips unnecessary JavaScript from the page, hydrating only the individual components that need it. This feature is called [partial hydration](/core-concepts/component-hydration).
|
||||
|
||||
Next.js doesn't support partial hydration, and instead makes the user load and rehydrate the entire page in the browser, even if most of the page content is static. This creates a slower page load and worse performance for your website. Next.js has [experimental support](https://piccalil.li/blog/new-year-new-website/#heading-no-client-side-react-code) for fully-static, zero-JavaScript pages. However, there is no planned support for hydrating individual components on the page. This leaves you with an all-or-nothing decision for interactivity on each page.
|
||||
Next.js doesn't support partial hydration, and instead has the user load and rehydrate the entire page in the browser, even if most of the page content is static. This creates a slower page load and worse performance for your website. Next.js has [experimental support](https://piccalil.li/blog/new-year-new-website/#heading-no-client-side-react-code) for fully-static, zero-JavaScript pages. However, there is no planned support for hydrating individual components on the page. This leaves you with an all-or-nothing decision for interactivity on each page.
|
||||
|
||||
Next.js has great built-in image optimizations, which could make Next.js a better choice for some image-heavy websites.
|
||||
|
||||
|
@ -165,15 +136,15 @@ Next.js has great built-in image optimizations, which could make Next.js a bette
|
|||
[nextjs.org/docs](https://nextjs.org/docs/getting-started) is the official Next.js documentation website, built with Next.js. The website offers a similar enough design and featureset to compare against the official Astro documentation website. This gives us a **_rough, real-world_** comparison between the two site builders for this common use-case.
|
||||
|
||||
- **Next.js performance score**: 59 out of 100 [(full audit)](https://lighthouse-dot-webdotdevsite.appspot.com//lh/html?url=https%3A%2F%2Fnextjs.org%2Fdocs%2Fgetting-started)
|
||||
- **Astro performance score**: 99 out of 100 [(full audit)](https://lighthouse-dot-webdotdevsite.appspot.com//lh/html?url=https%3A%2F%2Fdocs.astro.build%2Fgetting-started)
|
||||
- **Astro performance score**: 95 out of 100 [(full audit)](https://lighthouse-dot-webdotdevsite.appspot.com//lh/html?url=https%3A%2F%2Fdocs.astro.build%2Fgetting-started)
|
||||
|
||||
One big reason behind this performance difference is Astro's smaller JavaScript payload: [nextjs.org/docs](https://nextjs.org/docs/getting-started) loads **463kb** of JavaScript on first page load while [docs.astro.build](https://docs.astro.build) loads **78.7kb** (83% less JavaScript, overall) _after_ first load.
|
||||
One big reason behind this performance difference is Astro's smaller JavaScript payload: [nextjs.org/docs](https://nextjs.org/docs/getting-started) loads **463kb** of JavaScript on first load while [docs.astro.build](https://docs.astro.build) only loads **9.3kb** (98% less JavaScript, overall).
|
||||
|
||||
## Nuxt vs. Astro
|
||||
|
||||
[Nuxt](https://nuxtjs.org/) is a popular website & application framework for Vue. It is similar to Next.js.
|
||||
[Nuxt](https://nextjs.org/) is a popular website & application framework for Vue. It is similar to Next.js.
|
||||
|
||||
Nuxt uses Vue to render your website. Astro is more flexible: you are free to build UI with any popular component library (React, Preact, Vue, Svelte, Solid and others) or Astro's HTML-like component syntax which is similar to HTML + JSX.
|
||||
Nuxt uses Vue to render your website. Astro is more flexible: you can use any UI component libraries (React, Preact, Vue, Svelte, and others) or Astro's built-in component syntax that is similar to HTML/JSX.
|
||||
|
||||
Both Nuxt and Astro are frameworks for building websites. Nuxt does best with highly dynamic websites (like dashboards and inboxes) while Astro does best with highly static websites (like content and eCommerce websites).
|
||||
|
||||
|
@ -183,7 +154,7 @@ Nuxt supports both Static Site Generation (SSG) and Server-Side Rendering (SSR).
|
|||
|
||||
In most cases, Astro websites will load significantly faster than Nuxt websites. This is because Astro automatically strips unnecessary JavaScript from the page, hydrating only the individual components that need it. This feature is called [partial hydration](/core-concepts/component-hydration).
|
||||
|
||||
Nuxt doesn't support partial hydration, and instead makes the user load and rehydrate the entire page in the browser, even if most of the page content is static. This creates a slower page load and worse performance for your website. There is no way to disable this behavior in Nuxt.
|
||||
Nuxt doesn't support partial hydration, and instead has the user load and rehydrate the entire page in the browser, even if most of the page content is static. This creates a slower page load and worse performance for your website. There is no way to disable this behavior in Nuxt.
|
||||
|
||||
Nuxt has great built-in image optimizations, which could make Nuxt a better choice for some image-heavy websites.
|
||||
|
||||
|
@ -192,29 +163,27 @@ Nuxt has great built-in image optimizations, which could make Nuxt a better choi
|
|||
[nuxtjs.org/docs](https://nuxtjs.org/docs/2.x/get-started/installation) is the official Nuxt documentation website, built with Nuxt. The website offers a similar enough design and featureset to compare against the official Astro documentation website. This gives us a **_rough, real-world_** comparison between the two site builders for this common use-case.
|
||||
|
||||
- **Nuxt performance score**: 48 out of 100 [(full audit)](https://lighthouse-dot-webdotdevsite.appspot.com//lh/html?url=https%3A%2F%2Fnuxtjs.org%2Fdocs%2F2.x%2Fget-started%2Finstallation)
|
||||
- **Astro performance score**: 99 out of 100 [(full audit)](https://lighthouse-dot-webdotdevsite.appspot.com//lh/html?url=https%3A%2F%2Fdocs.astro.build%2Fgetting-started)
|
||||
- **Astro performance score**: 95 out of 100 [(full audit)](https://lighthouse-dot-webdotdevsite.appspot.com//lh/html?url=https%3A%2F%2Fdocs.astro.build%2Fgetting-started)
|
||||
|
||||
One big reason behind this performance difference is Astro's smaller JavaScript payload: [nuxtjs.org/docs](https://nuxtjs.org/docs/2.x/get-started/installation) loads **469kb** of JavaScript on first page load while [docs.astro.build](https://docs.astro.build) loads **78.7kb** (83% less JavaScript), _after_ first load.
|
||||
One big reason behind this performance difference is Astro's smaller JavaScript payload: [nuxtjs.org/docs](https://nuxtjs.org/docs/2.x/get-started/installation) loads **469kb** of JavaScript on first load while [docs.astro.build](https://docs.astro.build) only loads **9.3kb** (98% less JavaScript, overall).
|
||||
|
||||
## VuePress vs. Astro
|
||||
|
||||
[VuePress](https://vuepress.vuejs.org/guide/) is a popular documentation website builder from the creators of Vue.js. VuePress uses Vue.js to generate your website UI while Astro supports React, Vue.js, Svelte, and raw HTML templating.
|
||||
[VuePress](https://vuepress.vuejs.org/guide/) is a popular documentation website builder. VuePress uses Vue.js to generate your website UI while Astro supports React, Vue.js, Svelte, and raw HTML templating.
|
||||
|
||||
VuePress was designed for documentation websites and has some built-in, documentation-specific website features that Astro does not support out of the box. Instead, Astro offers documentation-specific features through an official [`docs`](https://github.com/snowpackjs/astro/tree/main/examples/docs) theme that you can use for your site. This website was built using that template!
|
||||
|
||||
Evan You (creator of Vue.js) is currently working on a new version of Vuepress called [VitePress.](https://vitepress.vuejs.org/). If you want a modern alternative to VuePress, [check out Evan's post](https://github.com/snowpackjs/astro/issues/1159#issue-974035962) on why VitePress may be a better option.
|
||||
VuePress was designed to build documentation websites and has some built-in, documentation-specific website features that Astro does not. Instead, Astro offers documentation-specific features through an official [`docs`](https://github.com/snowpackjs/astro/tree/main/examples/docs) theme that you can use for your site. This website was built using that template!
|
||||
|
||||
#### Comparing VuePress vs. Astro Performance
|
||||
|
||||
In most cases, Astro websites will load significantly faster than VuePress websites. This is because Astro automatically strips unnecessary JavaScript from the page, hydrating only the individual components that need it. This feature is called [partial hydration](/core-concepts/component-hydration).
|
||||
|
||||
VuePress doesn't support partial hydration, and instead makes the user load and rehydrate the entire page in the browser, even if most of the page content is static. This creates a slower page load and worse performance for your website. There is no way to disable this behavior in VuePress.
|
||||
VuePress doesn't support partial hydration, and instead has the user load and rehydrate the entire page in the browser, even if most of the page content is static. This creates a slower page load and worse performance for your website. There is no way to disable this behavior in VuePress.
|
||||
|
||||
#### Case Study: Building a Documentation Website
|
||||
|
||||
[vuepress.vuejs.org](https://vuepress.vuejs.org/guide/) is the official VuePress documentation website, built with VuePress. The website offers a similar enough design and featureset to compare against the official Astro documentation website. This gives us a **_rough, real-world_** comparison between the two site builders for this common use-case.
|
||||
|
||||
- **Vuepress performance score**: 63 out of 100 [(full audit)](https://lighthouse-dot-webdotdevsite.appspot.com//lh/html?url=https%3A%2F%2Fvuepress.vuejs.org%2Fguide%2F)
|
||||
- **Astro performance score**: 99 out of 100 [(full audit)](https://lighthouse-dot-webdotdevsite.appspot.com//lh/html?url=https%3A%2F%2Fdocs.astro.build%2Fgetting-started)
|
||||
- **Astro performance score**: 95 out of 100 [(full audit)](https://lighthouse-dot-webdotdevsite.appspot.com//lh/html?url=https%3A%2F%2Fdocs.astro.build%2Fgetting-started)
|
||||
|
||||
One big reason behind this performance difference is Astro's smaller JavaScript payload: [vuepress.vuejs.org](https://vuepress.vuejs.org/guide/) loads **166kb** of JavaScript on first page load while [docs.astro.build](https://docs.astro.build) loads **78.7kb** (53% less JavaScript, overall) _after_ first load.
|
||||
One big reason behind this performance difference is Astro's smaller JavaScript payload: [vuepress.vuejs.org](https://vuepress.vuejs.org/guide/) loads **166kb** of JavaScript on first load while [docs.astro.build](https://docs.astro.build) only loads **9.3kb** (95% less JavaScript, overall).
|
|
@ -166,9 +166,7 @@ const { greeting = 'Hello', name } = Astro.props;
|
|||
</div>
|
||||
```
|
||||
|
||||
You can define your props with TypeScript by exporting a `Props` type interface.
|
||||
|
||||
> _**In the future**_, Astro will automatically pick up any exported `Props` interface and give type warnings/errors for your project.
|
||||
You can define your props with TypeScript by exporting a `Props` type interface. In the future, Astro will automatically pick up any exported `Props` interface and give type warnings/errors for your project.
|
||||
|
||||
```astro
|
||||
---
|
||||
|
@ -275,39 +273,6 @@ const items = ["Dog", "Cat", "Platipus"];
|
|||
</ul>
|
||||
```
|
||||
|
||||
### Hoisted scripts
|
||||
|
||||
By default Astro does not make any assumptions on how you want scripts to be served, so if you add a `<script>` tag in a page or a component it will be left alone.
|
||||
|
||||
However if you'd like all of your scripts to be hoisted out of components and moved to the top of the page, and then later bundled together in production, you can achieve this with hoisted scripts.
|
||||
|
||||
A **hoisted script** looks like this:
|
||||
|
||||
```astro
|
||||
<script hoist>
|
||||
// An inline script
|
||||
</script>
|
||||
```
|
||||
|
||||
Or it can link to an external JavaScript file:
|
||||
|
||||
```astro
|
||||
<script src={Astro.resolve('./my-component.js')} hoist></script>
|
||||
```
|
||||
|
||||
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. -->
|
||||
<TwitterTimeline />
|
||||
<TwitterTimeline />
|
||||
<TwitterTimeline />
|
||||
```
|
||||
|
||||
## 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
|
|||
<img src="/thumbnail.png" />
|
||||
```
|
||||
|
||||
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
|
||||
|
292
docs/src/pages/group-1/core-concepts/collections.md
Normal file
292
docs/src/pages/group-1/core-concepts/collections.md
Normal file
|
@ -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 */ };
|
||||
}
|
||||
---
|
||||
<!-- Not shown: Page HTML template -->
|
||||
```
|
||||
|
||||
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;
|
||||
---
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>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</title>
|
||||
</head>
|
||||
<body>
|
||||
{posts.data.map((post) => (
|
||||
<h1>{post.title}</h1>
|
||||
<time>{formatDate(post.published_at)}</time>
|
||||
<a href={post.url}>Read Post</a>
|
||||
))}
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
## 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;
|
||||
---
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>Pagination Example: Page Number {posts.page.current}</title>
|
||||
<link rel="canonical" href={posts.url.current} />
|
||||
<link rel="prev" href={posts.url.prev} />
|
||||
<link rel="next" href={posts.url.next} />
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h5>Results {posts.start + 1}–{posts.end + 1} of {posts.total}</h5>
|
||||
</main>
|
||||
<footer>
|
||||
<h4>Page {posts.page.current} / {posts.page.last}</h4>
|
||||
<nav class="nav">
|
||||
<a class="prev" href={posts.url.prev || '#'}>Prev</a>
|
||||
<a class="next" href={posts.url.next || '#'}>Next</a>
|
||||
</nav>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
## 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 <channel>
|
||||
customData: `<language>en-us</language>
|
||||
<itunes:author>The Sunset Explorers</itunes:author>`,
|
||||
// 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: ``<id>${Astro.site}collection/${item.id}</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 `<link>` tags manually in your `<head>` HTML for feed readers and browsers to pick up:
|
||||
|
||||
```html
|
||||
<link
|
||||
rel="alternate"
|
||||
type="application/rss+xml"
|
||||
title="My RSS Feed"
|
||||
href="/feed/podcast.xml"
|
||||
/>
|
||||
```
|
||||
|
||||
### 📚 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)
|
|
@ -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.
|
||||
|
||||
### `<MyComponent client:only />`
|
||||
|
||||
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. `<client:only="my-custom-renderer" />`.
|
||||
|
||||
## 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.
|
69
docs/src/pages/group-1/de/getting-started.md
Normal file
69
docs/src/pages/group-1/de/getting-started.md
Normal file
|
@ -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 `<Markdown />` und `<Prism />`.
|
||||
|
||||
### 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/).
|
|
@ -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 `<Markdown />` y `<Code />`.
|
||||
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 `<Markdown/>` y `<Prism/>`.
|
||||
|
||||
### 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/).
|
|
@ -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 `<Markdown />` ja `<Code />`.
|
||||
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 `<Markdown />` ja `<Prism />`.
|
||||
|
||||
### Dokumentaation versioinnista
|
||||
|
|
@ -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"
|
||||
},
|
||||
}
|
||||
```
|
|
@ -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.
|
|
@ -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 `<Markdown />` and `<Code />`.
|
||||
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 `<Markdown />` and `<Prism />`.
|
||||
|
||||
### Versioned Documentation
|
||||
|
|
@ -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 \<YOUR USERNAME\>.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 \<YOUR USERNAME\>.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!
|
|
@ -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 `<slot />` 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 `<slot />` element.
|
||||
|
||||
`src/layouts/main.astro`
|
||||
|
||||
```jsx
|
||||
// src/layouts/BaseLayout.astro
|
||||
---
|
||||
const { content } = Astro.props;
|
||||
---
|
||||
|
||||
<html>
|
||||
<head>
|
||||
<title>{content.title}</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<slot />
|
||||
<slot/>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
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 `<Markdown>` 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';
|
|||
</Layout>
|
||||
````
|
||||
|
||||
## 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.
|
||||
|
||||
<Markdown content={content} />
|
||||
</Markdown>
|
||||
</Mardown>
|
||||
</Layout>
|
||||
```
|
||||
|
||||
## Security FAQs
|
||||
### Security FAQs
|
||||
|
||||
**Aren't there security concerns to rendering remote markdown directly to HTML?**
|
||||
|
|
@ -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)
|
||||
|
|
@ -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: `<link rel="stylesheet" href="{Astro.resolve('../styles/global.css')}">` — **not** `<link rel="stylesheet" href="{Astro.resolve('../styles/global.scss')}">`.
|
||||
**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: `<link rel="stylesheet" href="/style/global.css">` — **not** `<link rel="stylesheet" href="/style/global.scss">`.
|
||||
|
||||
### 🍃 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 `<style>` tags, but be mindful of duplication! If you end up creating multiple Tailwind-managed stylesheets for your site, make sure you're not sending the same CSS to users over and over again in separate CSS files.
|
||||
|
||||
#### Migrating from v0.19
|
||||
|
||||
As of [version 0.20.0](https://github.com/snowpackjs/astro/releases/tag/astro%400.20.0), Astro will no longer bundle, build and process `public/` files. Previously, we'd recommended putting your tailwind files in the `public/` directory. If you started a project with this pattern, you should move any Tailwind styles into the `src` directory and import them in your template using [Astro.resolve()](/reference/api-reference#astroresolve):
|
||||
|
||||
```astro
|
||||
<link
|
||||
rel="stylesheet"
|
||||
href={Astro.resolve("../assets/global.css")}
|
||||
>
|
||||
```
|
||||
As an alternative to `public/global.css`, You may also add Tailwind utilities to individual `pages/*.astro` components in `<style>` tags, but be mindful of duplication! If you end up creating multiple Tailwind-managed stylesheets for your site, make sure you're not sending the same CSS to users over and over again in separate CSS files.
|
||||
|
||||
### Importing from npm
|
||||
|
||||
|
@ -285,7 +272,7 @@ import Button from './Button.astro';
|
|||
</nav>
|
||||
```
|
||||
|
||||
This is undesirable because now `<Nav>` and `<Button>` fight over what the final button looks like. Now, whenever you edit one, you'll always have to edit the other, and they are no longer truly isolated as they once were (now coupled by a bidirectional styling dependency). It's easy to see how this pattern only has to be repeated a couple times before being afraid that touching any styles _anywhere_ may break styling in a completely different part of the app (queue `peter-griffin-css-blinds.gif`).
|
||||
This is undesirable because now `<Nav>` and `<Button>` fight over what the final button looks like. Now, whenever you edit one, you'll always have to edit the other, and they are no longer truly isolated as they once were (now coupled by a bidirectional styling dependency). It's easy to see how this pattern only has to repeated a couple times before being afraid that touching any styles _anywhere_ may break styling in a completely different part of the app (queue `peter-griffin-css-blinds.gif`).
|
||||
|
||||
Instead, let `<Button>` control its own styles, and try a prop:
|
||||
|
||||
|
@ -316,7 +303,7 @@ Elsewhere, you can use `<Button theme="nav">` to set the type of button it is. T
|
|||
|
||||
Recently there has been a debate of all-scoped component styles vs utility-only CSS. But we agree with people like Sarah Dayan who ask [why can't we have both][utility-css]? Truth is that while having scoped component styles are great, there are still hundreds of times when the website's coming together when two components just don't line up _quite_ right, and one needs a nudge. Or different text treatment is needed in one component instance.
|
||||
|
||||
While the thought of having perfect, pristine components is nice, it's unrealistic. No design system is absolutely perfect, and every design system has inconsistencies. And it's in reconciling these inconsistencies where components can become a mess without utility CSS. Utility CSS is great for adding minor tweaks necessary to get the website out the door. But they also are incomplete on their own—if you've ever tried to manage responsive styles or accessible focus states with utility CSS it can quickly become a mess! **Utility CSS works best in partnership with component (scoped) CSS**. And in order to be as easy as possible to use, Utility CSS should be global (arguably should be your only global CSS, besides maybe reset.css) so you don't have to deal with imports all willy-nilly.
|
||||
While the thought of having perfect, pristine components is nice, it's unrealistic. No design system is absoutely perfect, and every design system has inconsistencies. And it's in reconciling these inconsistencies where components can become a mess without utility CSS. Utility CSS is great for adding minor tweaks necessary to get the website out the door. But they also are incomplete on their own—if you've ever tried to manage responsive styles or accessible focus states with utility CSS it can quickly become a mess! **Utility CSS works best in partnership with component (scoped) CSS**. And in order to be as easy as possible to use, Utility CSS should be global (arguably should be your only global CSS, besides maybe reset.css) so you don't have to deal with imports all willy-nilly.
|
||||
|
||||
Some great problems best handled with Utility CSS are:
|
||||
|
||||
|
@ -337,13 +324,15 @@ In Astro, we recommend the following setup for this:
|
|||
And in your local filesystem, you can even use Sass' [@use][sass-use] to combine files together effortlessly:
|
||||
|
||||
```
|
||||
├── src/
|
||||
├── public/
|
||||
│ └── styles/
|
||||
│ ├── _base.scss
|
||||
│ ├── _tokens.scss
|
||||
│ ├── _typography.scss
|
||||
│ ├── _utils.scss
|
||||
│ └── global.scss
|
||||
└── src/
|
||||
└── (pages)
|
||||
```
|
||||
|
||||
What's in each file is up to you to determine, but start small, add utilities as you need them, and you'll keep your CSS weight incredibly low. And utilities you wrote to meet your real needs will always be better than anything off the shelf.
|
|
@ -1,12 +1,12 @@
|
|||
---
|
||||
import Layout from '../layouts/MainLayout.astro';
|
||||
import Layout from '../../layouts/MainLayout.astro';
|
||||
---
|
||||
|
||||
<script>
|
||||
// WIP: trigger a client-side redirect based on the browser language.
|
||||
// This is some wip redirect code based on the browser language.
|
||||
// A vercel.json redirect is enforced in production, so no user should ever see this page.
|
||||
// Remove the vercel.json redirect when this is ready.
|
||||
const KNOWN_LANGUAGES = ['bg', 'de','en','es','fi','nl','pt-br','zh-CN','zh-TW', 'fr', 'kr', 'da'];
|
||||
const KNOWN_LANGUAGES = ['de','en','es','fi','nl','pt-br','zh-CN','zh-TW'];
|
||||
let newLangWithRegion = (window.navigator.userLanguage || window.navigator.language || 'en-US').substr(0, 5);
|
||||
let newLang = newLangWithRegion.substr(0, 2);
|
||||
if (newLang === 'en') {
|
||||
|
@ -18,4 +18,4 @@ import Layout from '../layouts/MainLayout.astro';
|
|||
} else {
|
||||
window.location.pathname = '/getting-started';
|
||||
}
|
||||
</script>
|
||||
</script>
|
|
@ -25,7 +25,7 @@ npm init astro
|
|||
yarn create astro
|
||||
```
|
||||
|
||||
[`create-astro`](https://github.com/snowpackjs/astro/tree/main/packages/create-astro) wizard lets you choose from a set of [starter templates](/examples) or alternatively, you could import your own Astro project directly from GitHub.
|
||||
[`create-astro`](https://github.com/snowpackjs/astro/tree/main/packages/create-astro) wizard lets you choose from a set of [starter templates](/examples) or alternatively, you could import your own Astro project directly from Github.
|
||||
|
||||
```bash
|
||||
# Note: Replace "my-astro-project" with the name of your project.
|
||||
|
@ -48,11 +48,11 @@ After `create-astro` scaffolds out your project, remember to install your projec
|
|||
npm install
|
||||
```
|
||||
|
||||
You can now [Start](#start-astro) your Astro project. Once you have completed assembling your Astro project you can then [Build](#build-astro) your project. Astro would then package up your application and have the static files ready for you to [Deploy](/guides/deploy) to your favourite hosting provider.
|
||||
You can now [Start](#start-astro) your Astro project. Once you have completed assembling your Astro project you can then [Build](#build-astro) your project. Astro would then package up your application and have the static files ready for you to [Deploy](/guides/deploy) to your favourite hosting provider
|
||||
|
||||
## Manual Install
|
||||
|
||||
You can also set up Astro without the aide of the `create-astro` wizard, below are the few extra steps that are required to get Astro going.
|
||||
You can also setup Astro without the aide of the `create-astro` wizard, below are the few extra steps that are required to get Astro going.
|
||||
|
||||
### Set up your project
|
||||
|
||||
|
@ -75,7 +75,7 @@ Astro is designed to work with the entirety of the npm package ecosystem. This i
|
|||
|
||||
### Install Astro
|
||||
|
||||
Following the instructions above, you should have a directory with a single `package.json` file inside of it. You can now set up Astro inside your project.
|
||||
Following the instructions above, you should have a directory with a single `package.json` file inside of it. You can now setup Astro inside your project.
|
||||
|
||||
```bash
|
||||
npm install astro
|
||||
|
@ -86,14 +86,13 @@ You can now replace the placeholder "scripts" section of your `package.json` fil
|
|||
```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"
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
The [`dev`](#start-astro) command launches the Astro Dev Server on `http://localhost:3000`. Once your project is ready, the [`build`](#build-astro) command outputs your project to the `dist/` directory. [Read more about deploying Astro in the Deploy guide.](/guides/deploy)
|
||||
The [`start`](#start-astro) command launches the Astro Dev Server on `http://localhost:3000`. Once your project is ready, the [`build`](#build-astro) command outputs your project to the `dist/` directory. [Read more about deploying Astro in the Deploy guide.](/guides/deploy)
|
||||
|
||||
### Create your first page
|
||||
|
||||
|
@ -136,7 +135,7 @@ You can create more pages in the `src/pages` directory, and Astro will use the f
|
|||
## [Start Astro](#start-astro)
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
npm start
|
||||
```
|
||||
|
||||
Astro will now start serving your application on `http://localhost:3000`. By opening this URL in your browser, you should see the Astro's “Hello, World”
|
|
@ -12,32 +12,32 @@ Benieuwd naar een snel overzicht van wat Astro is? [Bezoek onze homepage.](https
|
|||
|
||||
De gemakkelijkste manier om Astro te proberen, is door `npm init astro` uit te voeren in een nieuwe map op je computer. Deze CLI odpracht helpt je in verschillende stappen je eerste Astro project op te zetten.
|
||||
|
||||
Lees onze [installatiegids](/installation) voor een volledige uitleg over hoe je met Astro aan de slag kunt.
|
||||
Lees onze [installatiegids](/installation) voor een volledige uitleg over hoe u met Astro aan de slag kunt.
|
||||
|
||||
### Online Playgrounds
|
||||
|
||||
Als je interesse hebt om Astro online uit te proberen in je browser, kun je een online playground gebruiken. Probeer een Hello World voorbeeld op [CodeSandbox](https://codesandbox.io/s/astro-template-hugb3).
|
||||
Als je interesse hebt om Astro online uit te proberen in je browser, kun je de een online playground gebruiken. Probeer een Hello World voorbeeld op [CodeSandbox](https://codesandbox.io/s/astro-template-hugb3).
|
||||
|
||||
_Opmerking: sommige functies (bv. Snel vernieuwen) zijn momenteel beperkt op CodeSandbox._
|
||||
_Opmerking: sommige functies (bv. Snel vernieuwen) zijn momenteel beperk op CodeSandbox._
|
||||
|
||||
## Astro leren
|
||||
## Astor leren
|
||||
|
||||
Mensen komen naar Astro vanuit verschillende achtergronden en met verschillende leerstijlen. Of je nu de voorkeur geeft aan een meer theoretische of praktische benadering, we hopen dat je deze sectie nuttig zult vinden.
|
||||
Mensen komen naar Astro vanuit verschillende achtergronden en met verschillende leerstijlen. Of u nu de voorkeur geeft aan een meer theoretische of praktische benadering, we hopen dat je deze sectie nuttig zult vinden.
|
||||
|
||||
- Als je liever **leert door te doen**, begin dan met onze [voorbeeldenbibliotheek](https://github.com/snowpackjs/astro/tree/main/examples).
|
||||
- Als je de concepten liever **stap voor stap leert**, begin dan met onze [basisconcepten en handleidingen](/core-concepts/project-structure).
|
||||
- Als u de concepten liever **stap voor stap leert**, begin dan met onze [basisconcepten en handleidingen](/core-concepts/project-structure).
|
||||
|
||||
Zoals elke onbekende technologie heeft Astro een leercurve. Met wat oefening en wat geduld krijg je het onder de knie.
|
||||
|
||||
### Leer de `.astro` syntax
|
||||
|
||||
Wanneer je Astro begint te leren, zul je veel bestanden zien die de `.astro` bestandsextensie gebruiken. Dit is de syntax van de **Astro-component**: een speciaal HTML-achtig bestandsformaat dat Astro gebruikt voor sjablonen. Het is ontworpen om vertrouwd te voelen voor iedereen met HTML- of JSX-ervaring.
|
||||
Wanneer u Astro begint te leren, zult u veel bestanden zien die de `.astro` bestandsextensie gebruiken. Dit is de syntax van de **Astro-component**: een speciaal HTML-achtig bestandsformaat dat Astro gebruikt voor sjablonen. Het is ontworpen om vertrouwd te voelen voor iedereen met HTML- of JSX-ervaring.
|
||||
|
||||
Onze gids over [Astro-componenten](/core-concepts/astro-components) helpt je door de nieuwe `.astro` syntax en is de beste manier om te leren.
|
||||
|
||||
### API referentie
|
||||
|
||||
Deze documentatiesectie is handig als je meer details wilt weten over een bepaalde Astro API. [Configuratie referentie](/reference/configuration-reference) vermeldt bijvoorbeeld alle mogelijke configuratieopties die beschikbaar zijn. [Ingebouwde Componenten Referentie](/reference/builtin-components) geeft een overzicht van alle beschikbare kerncomponenten, zoals <Markdown /> en <Code />.
|
||||
Deze documentatiesectie is handig als je meer details wilt weten over een bepaalde Astro API. [Configuratie referentie](/reference/configuration-reference) vermeldt bijvoorbeeld alle mogelijke configuratieopties die beschikbaar zijn. [Ingebouwde Componenten Referentie](/reference/builtin-components) geeft een overzicht van alle beschikbare kerncomponenten, zoals <Markdown /> en <Prism />.
|
||||
|
||||
### Documentatie versies
|
||||
|
|
@ -39,7 +39,7 @@ Nosso guia útil em [componentes Astro](/core-concepts/astro-components) apresen
|
|||
|
||||
### Referência da API
|
||||
|
||||
Esta seção de documentação é útil quando você deseja aprender mais detalhes sobre uma determinada API do Astro. Por exemplo, [Referência de Configuração](/reference/configuration-reference) lista todas as opções de configuração possíveis disponíveis para você. [Referência de componentes incorporados](/reference/builtin-components) listas todos os componentes base disponíveis, como `<Markdown />` e `<Code />`.s
|
||||
Esta seção de documentação é útil quando você deseja aprender mais detalhes sobre uma determinada API do Astro. Por exemplo, [Referência de Configuração](/reference/configuration-reference) lista todas as opções de configuração possíveis disponíveis para você. [Referência de componentes incorporados](/reference/builtin-components) listas todos os componentes base disponíveis, como `<Markdown />` e `<Prism />`.s
|
||||
|
||||
### Documentação por Versão
|
||||
|
|
@ -17,7 +17,7 @@ npm init astro
|
|||
npm install
|
||||
|
||||
# start developing!
|
||||
npm run dev
|
||||
npm start
|
||||
|
||||
# when you're ready: build your static site to `dist/`
|
||||
npm run build
|
||||
|
@ -30,7 +30,7 @@ If you wish to learn more about the range of methods to install and setup Astro
|
|||
From inside your project directory, enter the following command into your terminal:
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
npm start
|
||||
```
|
||||
|
||||
Astro will now start serving your application on [http://localhost:3000](http://localhost:3000). Opening this URL in your browser, you should see the Astro's "Hello, World".
|
196
docs/src/pages/group-1/reference/api-reference.md
Normal file
196
docs/src/pages/group-1/reference/api-reference.md
Normal file
|
@ -0,0 +1,196 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: API Reference
|
||||
---
|
||||
|
||||
## `Astro` global
|
||||
|
||||
The `Astro` global is available in all contexts in `.astro` files. It has the following functions:
|
||||
|
||||
### `Astro.fetchContent()`
|
||||
|
||||
`Astro.fetchContent()` is a way to load local `*.md` files into your static site setup. You can either use this on its own, or within [Astro Collections](/core-concepts/collections).
|
||||
|
||||
```jsx
|
||||
// ./src/components/my-component.astro
|
||||
---
|
||||
const data = Astro.fetchContent('../pages/post/*.md'); // returns an array of posts that live at ./src/pages/post/*.md
|
||||
---
|
||||
|
||||
<div>
|
||||
{data.slice(0, 3).map((post) => (
|
||||
<article>
|
||||
<h1>{post.title}</h1>
|
||||
<p>{post.description}</p>
|
||||
<a href={post.url}>Read more</a>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
```
|
||||
|
||||
`.fetchContent()` only takes one parameter: a relative URL glob of which local files you'd like to import. Currently only `*.md` files are supported. It's synchronous, and returns an array of items of type:
|
||||
|
||||
```js
|
||||
{
|
||||
/** frontmatter from the post.. example frontmatter:
|
||||
title: '',
|
||||
tag: '',
|
||||
date: '',
|
||||
image: '',
|
||||
author: '',
|
||||
description: '',
|
||||
**/
|
||||
astro: {
|
||||
headers: [], // an array of h1...h6 elements in the markdown file
|
||||
source: '' // raw source of the markdown file
|
||||
html: '' // rendered HTML of the markdown file
|
||||
},
|
||||
url: '' // the rendered path
|
||||
}[]
|
||||
```
|
||||
|
||||
### `Astro.request`
|
||||
|
||||
`Astro.request` returns an object with the following properties:
|
||||
|
||||
| Name | Type | Description |
|
||||
| :------------- | :---- | :---------------------------------------------- |
|
||||
| `url` | `URL` | The URL of the request being rendered. |
|
||||
| `canonicalURL` | `URL` | [Canonical URL][canonical] of the current page. |
|
||||
|
||||
⚠️ Temporary restriction: this is only accessible in top-level pages and not in sub-components.
|
||||
|
||||
### `Astro.site`
|
||||
|
||||
`Astro.site` returns a `URL` made from `buildOptions.site` in your Astro config. If undefined, this will return a URL generated from `localhost`.
|
||||
|
||||
## Collections API
|
||||
|
||||
A collection is any file in the `src/pages` directory that starts with a dollar sign (`$`) and includes an exported `createCollection` function in the component script.
|
||||
|
||||
Check out our [Astro Collections](/core-concepts/collections) guide for more information and examples.
|
||||
|
||||
### `createCollection()`
|
||||
|
||||
```jsx
|
||||
---
|
||||
export async function createCollection() {
|
||||
return { /* ... */ };
|
||||
}
|
||||
---
|
||||
<!-- Your HTML template here. -->
|
||||
```
|
||||
|
||||
⚠️ The `createCollection()` function executes in its own isolated scope before page loads. Therefore you can't reference anything from its parent scope, other than file imports. The compiler will warn if you break this requirement.
|
||||
|
||||
The `createCollection()` function should returns an object of the following shape:
|
||||
|
||||
| Name | Type | Description |
|
||||
| :--------- | :--------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `route` | `string` | **Required.** A route pattern for matching URL requests. This is used to generate the page URL in your final build. It must begin with the file name: for example, `pages/$tags.astro` must return a `route` that starts with `/tags/`. |
|
||||
| `paths` | `{params: Params}[]` | Return an array of all URL to be generated. |
|
||||
| `props` | `async ({ params, paginate }) => object` | **Required.** Load data for the page that will get passed to the page component as props. |
|
||||
| `paginate` | `boolean` | Optional: Enable automatic pagination. See next section. |
|
||||
| `rss` | [RSS](/reference/api-reference#rss-feed) | Optional: generate an RSS 2.0 feed from this collection ([docs](/reference/api-reference#rss-feed)) |
|
||||
|
||||
### Pagination
|
||||
|
||||
Enable pagination for a collection by returning `paginate: true` from `createCollection()`. This passes a `paginate()` argument to `props()` that you can use to return paginated data in your HTML template via props.
|
||||
|
||||
The `paginate()` function that you use inside of `props()` has the following interface:
|
||||
|
||||
```ts
|
||||
/* the "paginate()" passed to props({paginate}) */
|
||||
type PaginateFunction = (
|
||||
data: any[],
|
||||
args?: {
|
||||
/* pageSize: set the number of items to be shown on every page. Defaults to 10. */
|
||||
pageSize?: number;
|
||||
}
|
||||
) => PaginatedCollectionResult;
|
||||
|
||||
/* the paginated return value, aka the prop passed to every page in the collection. */
|
||||
interface PaginatedCollectionResult {
|
||||
/** result */
|
||||
data: any[];
|
||||
|
||||
/** metadata */
|
||||
/** the count of the first item on the page, starting from 0 */
|
||||
start: number;
|
||||
/** the count of the last item on the page, starting from 0 */
|
||||
end: number;
|
||||
/** total number of results */
|
||||
total: number;
|
||||
page: {
|
||||
/** the current page number, starting from 1 */
|
||||
current: number;
|
||||
/** number of items per page (default: 25) */
|
||||
size: number;
|
||||
/** number of last page */
|
||||
last: number;
|
||||
};
|
||||
url: {
|
||||
/** url of the current page */
|
||||
current: string;
|
||||
/** url of the previous page (if there is one) */
|
||||
prev: string | undefined;
|
||||
/** url of the next page (if there is one) */
|
||||
next: string | undefined;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
📚 Learn more about pagination (and see an example) in our [Astro Collections guide.](/core-concepts/collections).
|
||||
|
||||
### RSS
|
||||
|
||||
Create an RSS 2.0 feed for a collection by returning `paginate: true` & an `rss` object from `createCollection()`. The `rss` object will be used to generate the contents of the RSS XML file.
|
||||
|
||||
The `rss` object follows the `CollectionRSS`data type:
|
||||
|
||||
```ts
|
||||
export interface CollectionRSS<T = any> {
|
||||
/** (required) Title of the RSS Feed */
|
||||
title: string;
|
||||
/** (required) Description of the RSS Feed */
|
||||
description: string;
|
||||
/** Specify arbitrary metadata on opening <xml> tag */
|
||||
xmlns?: Record<string, string>;
|
||||
/** Specify custom data in opening of file */
|
||||
customData?: string;
|
||||
/** Return data about each item */
|
||||
item: (item: T) => {
|
||||
/** (required) Title of item */
|
||||
title: string;
|
||||
/** (required) Link to item */
|
||||
link: string;
|
||||
/** Publication date of item */
|
||||
pubDate?: Date;
|
||||
/** Item description */
|
||||
description?: string;
|
||||
/** Append some other XML-valid data to this item */
|
||||
customData?: string;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
📚 Learn more about RSS feed generation (and see an example) in our [Astro Collections guide.](/core-concepts/collections).
|
||||
|
||||
## `import.meta`
|
||||
|
||||
> In this section we use `[dot]` to mean `.`. This is because of a bug in our build engine that is rewriting `import[dot]meta[dot]env` if we use `.` instead of `[dot]`.
|
||||
|
||||
All ESM modules include a `import.meta` property. Astro adds `import[dot]meta[dot]env` through [Snowpack](https://www.snowpack.dev/).
|
||||
|
||||
**`import[dot]meta[dot]env[dot]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:
|
||||
|
||||
```jsx
|
||||
import { h } from 'preact';
|
||||
|
||||
export default function () {
|
||||
// Note: rewrite "[dot]" to "." for this to to work in your project.
|
||||
return import[dot]meta[dot]env[dot]SSR ? <div class="spinner"></div> : <FancyComponent />;
|
||||
}
|
||||
```
|
||||
|
||||
[canonical]: https://en.wikipedia.org/wiki/Canonical_link_element
|
32
docs/src/pages/group-1/reference/builtin-components.md
Normal file
32
docs/src/pages/group-1/reference/builtin-components.md
Normal file
|
@ -0,0 +1,32 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Built-In Components
|
||||
---
|
||||
|
||||
Astro includes several builtin components for you to use in your projects. All builtin components are available via `import {} from 'astro/components';`.
|
||||
|
||||
## `<Markdown />`
|
||||
|
||||
```astro
|
||||
---
|
||||
import { Markdown } from 'astro/components';
|
||||
---
|
||||
<Markdown>
|
||||
# Markdown syntax is now supported! **Yay!**
|
||||
</Markdown>
|
||||
```
|
||||
|
||||
See our [Markdown Guide](/guides/markdown-content) for more info.
|
||||
|
||||
<!-- TODO: We should move some of the specific component info here. -->
|
||||
|
||||
## `<Prism />`
|
||||
|
||||
```astro
|
||||
---
|
||||
import { Prism } from 'astro/components';
|
||||
---
|
||||
<Prism code={`const foo = 'bar';`} />
|
||||
```
|
||||
|
||||
This component provides syntax highlighting for code blocks. Since this never changes in the client it makes sense to use an Astro component (it's equally reasonable to use a framework component for this kind of thing; Astro is server-only by default for all frameworks!).
|
|
@ -9,6 +9,8 @@ title: CLI Reference
|
|||
|
||||
Runs the Astro development server. This starts an HTTP server that responds to requests for pages stored in `src/pages` (or which folder is specified in your [configuration](/reference/configuration-reference)).
|
||||
|
||||
See the [dev server](/reference/dev) docs for more information on how the dev server works.
|
||||
|
||||
**Flags**
|
||||
|
||||
#### `--port`
|
||||
|
@ -19,12 +21,6 @@ Specifies should port to run on. Defaults to `3000`.
|
|||
|
||||
Builds your site for production.
|
||||
|
||||
### `astro preview`
|
||||
|
||||
Start a local static file server to serve your built `dist/` directory. Useful for previewing your static build locally, before deploying it.
|
||||
|
||||
This command is meant for local testing only, and is not designed to be run in production. For help with production hosting, check out our guide on [Deploying an Astro Website](/guides/deploy).
|
||||
|
||||
## Global Flags
|
||||
|
||||
### `--config path`
|
35
docs/src/pages/group-1/reference/configuration-reference.md
Normal file
35
docs/src/pages/group-1/reference/configuration-reference.md
Normal file
|
@ -0,0 +1,35 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Configuration Reference
|
||||
---
|
||||
|
||||
To configure Astro, add an `astro.config.mjs` file in the root of your project. All settings are optional. Here are the defaults:
|
||||
|
||||
```js
|
||||
export default {
|
||||
projectRoot: '.', // Where to resolve all URLs relative to. Useful if you have a monorepo project.
|
||||
src: './src', // Path to Astro components, pages, and data
|
||||
pages: './src/pages', // Path to Astro/Markdown pages
|
||||
dist: './dist', // When running `astro build`, path to final static output
|
||||
public: './public', // A folder of static files Astro will copy to the root. Useful for favicons, images, and other files that don't need processing.
|
||||
buildOptions: {
|
||||
// site: '', // Your public domain, e.g.: https://my-site.dev/. Used to generate sitemaps and canonical URLs.
|
||||
sitemap: true, // Generate sitemap (set to "false" to disable)
|
||||
},
|
||||
devOptions: {
|
||||
port: 3000, // The port to run the dev server on.
|
||||
// tailwindConfig: '', // Path to tailwind.config.js if used, e.g. './tailwind.config.js'
|
||||
},
|
||||
// component renderers which are enabled by default
|
||||
renderers: [
|
||||
'@astrojs/renderer-svelte',
|
||||
'@astrojs/renderer-vue',
|
||||
'@astrojs/renderer-react',
|
||||
'@astrojs/renderer-preact',
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
## Snowpack Config
|
||||
|
||||
Astro is powered internally by Snowpack. You can configure Snowpack directly by creating a `snowpack.config.mjs` file. See [snowpack.dev](https://www.snowpack.dev/reference/configuration) for full documentation on this file.
|
|
@ -59,19 +59,18 @@ export default {
|
|||
snowpackPlugin: '@snowpack/plugin-xxx', // optional, the name of a snowpack plugin to inject
|
||||
snowpackPluginOptions: { example: true }, // optional, any options to be forwarded to the snowpack plugin
|
||||
knownEntrypoint: ['framework'], // optional, entrypoint modules that will be used by compiled source
|
||||
external: ['dep'], // optional, dependencies that should not be built by snowpack
|
||||
polyfills: ['./shadow-dom-polyfill.js'], // optional, module scripts that should be loaded before client hydration.
|
||||
hydrationPolyfills: ['./hydrate-framework.js'], // optional, polyfills that need to run before hydration ever occurs.
|
||||
external: ['dep'] // optional, dependencies that should not be built by snowpack
|
||||
polyfills: ['./shadow-dom-polyfill.js'] // optional, module scripts that should be loaded before client hydration.
|
||||
hydrationPolyfills: ['./hydrate-framework.js'] // optional, polyfills that need to run before hydration ever occurs.
|
||||
jsxImportSource: 'preact', // optional, the name of the library from which JSX is imported
|
||||
jsxTransformOptions: async () => {
|
||||
// optional, a function to transform JSX files
|
||||
const {
|
||||
default: { default: jsx },
|
||||
} = await import('@babel/plugin-transform-react-jsx');
|
||||
jsxTransformOptions: async () => { // optional, a function to transform JSX files
|
||||
const { default: { default: jsx }} = await import('@babel/plugin-transform-react-jsx');
|
||||
return {
|
||||
plugins: [jsx({}, { runtime: 'automatic', importSource: 'preact' })],
|
||||
};
|
||||
},
|
||||
plugins: [
|
||||
jsx({}, { runtime: 'automatic', importSource: 'preact' })
|
||||
]
|
||||
}
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
|
@ -128,7 +127,7 @@ export default {
|
|||
|
||||
`check` is a function that determines whether a Component should be "claimed" by this renderer.
|
||||
|
||||
In its simplest form, it can check for the existence of a flag on Object-based components.
|
||||
In it's simplest form, it can check for the existence of a flag on Object-based components.
|
||||
|
||||
```js
|
||||
function check(Component) {
|
|
@ -40,7 +40,7 @@ Astro 是一个现代的静态网站生成工具. 你可以从 [我们的主页]
|
|||
|
||||
### API 参考文档
|
||||
|
||||
当你想了解某个特定的 Astro API 的更多细节时,这部分文档是有用的。例如 [配置参考](/reference/configuration-reference) 列出所有可能的配置选项供你使用。 [内置组件参考](/reference/builtin-components) 列出了所有可用的核心组件,如`<Markdown />`和`<Code />`。
|
||||
当你想了解某个特定的 Astro API 的更多细节时,这部分文档是有用的。例如 [配置参考](/reference/configuration-reference) 列出所有可能的配置选项供你使用。 [内置组件参考](/reference/builtin-components) 列出了所有可用的核心组件,如`<Markdown />`和`<Prism />`。
|
||||
|
||||
### 其他版本文档
|
||||
|
|
@ -91,14 +91,13 @@ npm install astro
|
|||
```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"
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
[`dev`](#start-dev) 命令在 `http://localhost:3000` 上启动 Astro 开发服务器。一旦你的项目准备好了。
|
||||
[`start`](#start-astro) 命令在 `http://localhost:3000` 上启动 Astro 开发服务器。一旦你的项目准备好了。
|
||||
|
||||
[`build`](#build-astro)命令将你的项目输出到 `dist/` 目录。[在部署指南中阅读更多关于部署 Astro 的内容。](/guides/deploy)
|
||||
|
||||
|
@ -142,7 +141,7 @@ console.log('See me in the Terminal')
|
|||
## [启动 Astro](#start-astro)
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
npm start
|
||||
```
|
||||
|
||||
Astro 会开启预览服务器,地址为 [http://localhost:3000](http://localhost:3000),
|
|
@ -18,7 +18,7 @@ npm init astro
|
|||
npm install
|
||||
|
||||
# 启动项目
|
||||
npm run dev
|
||||
npm start
|
||||
|
||||
# 将项目打包到 dist 文件夹下
|
||||
npm run build
|
||||
|
@ -31,7 +31,7 @@ npm run build
|
|||
工程目录下终端输入以下命令:
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
npm start
|
||||
```
|
||||
|
||||
Astro 会开启预览服务器,地址为 [http://localhost:3000](http://localhost:3000),
|
63
docs/src/pages/group-1/zh-TW/getting-started.md
Normal file
63
docs/src/pages/group-1/zh-TW/getting-started.md
Normal file
|
@ -0,0 +1,63 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: 入門指南
|
||||
lang: zh-TW
|
||||
---
|
||||
|
||||
Astro 是一個現代的靜態網站生成工具. 你可以從 [我們的主頁](https://astro.build/) 或者 [我們的 release 公告](https://astro.build/blog/introducing-astro) 中瞭解到 Astro 的全部內容,本頁是 Astro 文檔和所有相關資源的概述。
|
||||
|
||||
想快速瞭解一下什麼是 Astro ? [瀏覽我們的主頁] (https://astro.build)
|
||||
|
||||
## 嘗試一下 Astro
|
||||
|
||||
嘗試 Astro 的最簡單的方法是在新目錄下運行 『npm init astro』。 我們的 CLI 工具會説明你創建啟動一個新的 Astro 專案。
|
||||
|
||||
想要快速了解學習使用 Astro, [快速入門指南](quick-start).
|
||||
|
||||
另外,請閱讀我們的 [安裝指南](/installation),瞭解如何使用 Astro 進行安裝的全部步驟。
|
||||
|
||||
### 在線遊樂場
|
||||
|
||||
如果你有興趣在瀏覽器中嘗試 Astro,你可以使用一個在線代碼遊樂場。 試試我們在 [CodeSandbox](https://codesandbox.io/s/astro-template-hugb3) 上的 "Hello World!" 範本。
|
||||
|
||||
注意:一些功能(例如:快速刷新)目前在 CodeSandbox 上是受限的。
|
||||
|
||||
## 學習 Astro
|
||||
|
||||
各種各樣的人來自不同的背景,帶來了不同的學習方式,來到 Astro。 無論你喜歡的是理論性強的方法還是實踐性強的方法,我們希望你會發現本節內容對你有説明。
|
||||
|
||||
- 如果你喜歡在**實踐中**學習,請從我們的 [實例庫](https://github.com/snowpackjs/astro/tree/main/examples) 開始學習。
|
||||
|
||||
- 如果你喜歡**逐步學習概念**,請從我們的[基本概念和指南](/core-concepts/project-structure)開始。
|
||||
|
||||
像任何不熟悉的技術一樣,Astro 也有一個輕量化的學習曲線。 然而我們相信只要有耐心勤於練習你很快就會掌握訣竅的。
|
||||
|
||||
### 學習 '.astro' 語法
|
||||
|
||||
當你開始學習 Astro 時,你會看到許多檔使用『.astro』檔擴展名。 這是**Astro 的元件語法**:一種特殊的類似 HTML 的檔格式,Astro 用於範本製作。 這樣設計是為了讓任何有 HTML 或 JSX 經驗的人更容易上手。
|
||||
|
||||
我們在 [Astro 元件](/corecepts/astro-components) 上的有用指南向你介紹了 Astro 語法,這也是學習的最好方法。
|
||||
|
||||
### API 參考文檔
|
||||
|
||||
當你想了解某個特定的 Astro API 的更多細節時,這部分文檔是有用的。 例如 [配置參考](/reference/configuration-reference) 列出所有可能的配置選項供你使用。 [內置元件參考] (/reference/builtin-components) 列出了所有可用的核心元件,如『<Markdown />』和『<Prism />』。
|
||||
|
||||
### 其他版本文檔
|
||||
|
||||
本文檔總是展示 Astro 的最新穩定版本。 一旦我們達到 V1.0 的里程碑,我們將增加查看版本檔的能力。
|
||||
|
||||
## 瞭解最新消息
|
||||
|
||||
[@astrodotbuild] (https://twitter.com/astrodotbuild) Twitter 帳戶是 Astro 團隊的官方更新來源。
|
||||
|
||||
我們也在我們的 [Discord 社區](https://astro.build/chat) 的 #announcements 頻道中發佈 release 公告。
|
||||
|
||||
當然並非每個 Astro 的發佈都會有自己的 release 公告,你可以在 Astro 倉庫的 ['CHANGELOG.md'檔](https://github.com/snowpackjs/astro/blob/main/packages/astro/CHANGELOG.md) 中找到每個版本的詳細更新日誌。
|
||||
|
||||
## 勘誤與建議
|
||||
|
||||
如果你在閱讀的過程中發現文檔中缺少什麼,或者你發現某些部分令人困惑,請 [為文檔提交問題](https://github.com/snowpackjs/astro/issues/new/choose) ,提出你的改進建議,或者在 [@astrodotbuild](https://twitter.com/astrodotbuild) Twitter 帳戶上發推文。 我們希望聽到你的建議!
|
||||
|
||||
## 參考
|
||||
|
||||
本入門指南最初是基於 [React](https://reactjs.org/) 的入門指南。
|
9
docs/src/pages/group-10/404.astro
Normal file
9
docs/src/pages/group-10/404.astro
Normal file
|
@ -0,0 +1,9 @@
|
|||
---
|
||||
import SplashLayout from '../../layouts/SplashLayout.astro';
|
||||
---
|
||||
|
||||
<SplashLayout title="Not Found">
|
||||
<h1>404</h1>
|
||||
<p>This page isn't in our solar system.</p>
|
||||
<a href="/">Take me home.</a>
|
||||
</SplashLayout>
|
241
docs/src/pages/group-10/blog/island-architecture.md
Normal file
241
docs/src/pages/group-10/blog/island-architecture.md
Normal file
|
@ -0,0 +1,241 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Island Architecture
|
||||
draft: true
|
||||
---
|
||||
|
||||
<!--
|
||||
@aFuzzyBear: I have been spending most the day learning more about Island Architecture, wrote plenty of notes, listened to Fred K Schott's interview on Speakeasy(https://www.youtube.com/watch?v=mgkwZqVkrwo) and the interview with Jason Lengstrof (https://www.youtube.com/watch?v=z15YLsLMtu4)
|
||||
Figured I might give writing this a wee go,
|
||||
|
||||
I wanted to take this from the direction of it being more of a critique of the past and present state of affairs in web dev
|
||||
Post structure:
|
||||
1)Start with an introduction to Islands Arch
|
||||
2)Talk about the different Architectures that can be used in Web-dev
|
||||
3)MVC/StaticSites - SPA's
|
||||
4)Frameworks, get some external links onto the page
|
||||
4)Moving to ESM
|
||||
5)Benefits of ESM
|
||||
6)
|
||||
|
||||
-->
|
||||
|
||||
<!-- Intro -->
|
||||
|
||||
> "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](<https://en.wikipedia.org/wiki/Hydration_(web_development)>) 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 `<script>` within our HTML document.
|
||||
|
||||
This means for our page, we need to wait for React to be fetched and downloaded, then parsed and executed, have it wait for the page to display the carousel before we receive the behaviour and functionality we expect from our small dynamic component.
|
||||
|
||||
Instead of this laborious process, one would simply render the carousel in HTML on the server and have a dedicated `<script>` that is emitted when the component for the carousel is displayed.
|
||||
|
||||
This would then load the functionality for the carousel in-place, transforming it instantly into a dynamic image slide show, with navigation.
|
||||
|
||||
## Island Hydration
|
||||
|
||||
By now the idea of Island-architecture must be settling in, and one must be thinking, this is just [Progressive Hydration](<https://en.wikipedia.org/wiki/Hydration_(web_development)#Progressive_rehydration>), and you wouldn't be overly off mark.
|
||||
|
||||
Progressive Hydration that is used in frameworks like: Angular, React, Preact, Vue. Are individual components, which are loaded and then initialised over a period of time.
|
||||
|
||||
Using scheduling processes, and accounting for things like viewport visibility, content value, probability of interaction etc. They can abstract away the intricacies and delivery this form of hydration for developers.
|
||||
|
||||
By using Island styled components, this form of hydration essentially comes for **free**.
|
||||
|
||||
Since the larger dynamic components on a page are being initialised separately, not progressively. The difference lets individual regions on the page to become interactive without the page requiring to first load anything.
|
||||
|
||||
This expands further, as it doesn't need any form of ['Top-down Rendering'](https://developers.google.com/web/fundamentals/performance/rendering).
|
||||
|
||||
Since there is no outer `<div id='root'>` element that needs to be initialised before the inner contents can be exposed.
|
||||
|
||||
Every region of the page is an isolated unit, an island, on its own, connected to others by the HTML page. With such an approach the benefits do begin to stack up.
|
||||
|
||||
A key benefit is seen with the site performance. Since isolation is inherent, if a single issue affects a component, it wouldn't affect the other _islands_ on the page.
|
||||
|
||||
## Exploring the Island
|
||||
|
||||
As we explore further into the Island, we can see immediate trade differences between framework produced SSR solutions and those that could be provided by using Island Architecture.
|
||||
|
||||
Quickly wandering back to the Status Quo for a brief interlude. We use SSR with SPA's to help tackle the downside of SPA's and its SEO. Appealing to the search engines in this manner has another negative effect on the UX.
|
||||
|
||||
> "...visitors are left waiting for the actual functionality of a page to arrive while staring at a frustratingly fake version of that page." - Jason Miller
|
||||
|
||||
There are other issues that stem from traditional SSR, and being idly unawares of such performance pitfalls, gives rise to an orchestra of potential problems.
|
||||
|
||||
Further compounded with misconceptions on implementations and utilisations of solid SSR techniques, this practice is increasingly prominent amongst the Status Quoticians.
|
||||
|
||||
The one most obvious drawback with SSR is the amount of work JS has to do during the initial page load, is far excessive than is necessary, and is extremely inefficient use of resources.
|
||||
|
||||
We find with our "Islands" model, that with Server rendering is a fundamental part of how pages are delivered to the browser.
|
||||
|
||||
The responded HTML, would still contain all the rendered content that the user requested. With some islands yet to engage their client-sided interactivity. The document sent should contain all the content that the User would need.
|
||||
|
||||
An example of this would be a product page for a e-commerce business. A product page, using the Islands model would contain that product's description, price etc, Having the dynamic components becoming interactive on demand.
|
||||
|
||||
We also discover that with the Islands model we have better accessibility and discoverability of our elements and the contents within.
|
||||
|
||||
Less code is eventually shipped from each island which is a massive cost-saving benefit.
|
||||
|
||||
However the conceptual idea of using Islands from a Web developers viewpoint is that, we get to come full circle and begin to deliver lightening fast user experiences without having the previous trade-offs and penalties that came from previous design models.
|
||||
|
||||
They're plenty of more important discoveries yet to be made when exploring the Island Architecture model in more detail.
|
||||
|
||||
Jason finished his post with the following:
|
||||
|
||||
> "It's possible...that adopting a model like this requires more up-front design thinking. There are far few batteries-included options available ...Who knows, maybe we can fix that." - August 2020
|
||||
|
||||
## Astrolands
|
||||
|
||||
<!-- Conclusion, final words. Here tie in Astro -->
|
||||
|
||||
Here at Astro, we fully embrace the principles ideas behind Jason's 'Island Architecture'. As a result, we have been hard at work trying to apply this new innovative concept into Web Development and the JS ecosystem.
|
||||
|
||||
We would like to take this time to encourage you to start exploring how Astro accomplishes this. And experience how easy it is to adopt as an architectural design philosophy.
|
189
docs/src/pages/group-10/comparing-astro-vs-other-tools.md
Normal file
189
docs/src/pages/group-10/comparing-astro-vs-other-tools.md
Normal file
|
@ -0,0 +1,189 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Comparing Astro
|
||||
---
|
||||
|
||||
We often get asked the question, "How does Astro compare to my favorite site builder, **\_\_\_\_**?" This guide was written to help answer that question for several popular site builders and Astro alternatives.
|
||||
|
||||
If you don't see your favorite site builder listed here, [ask us in Discord.](https://astro.build/chat)
|
||||
|
||||
## Project Status
|
||||
|
||||
A quick note on project maturity: **Astro is still in beta.** Many of the tools listed here are much more mature. Some predate Astro by over 12 years!
|
||||
|
||||
A few features are still missing from Astro, and several APIs are not yet finalized. However, the project is considered stable from a bug perspective and several production websites have already been built using Astro. This is an important point to consider when choosing Astro.
|
||||
|
||||
## Docusaurus vs. Astro
|
||||
|
||||
[Docusaurus](https://docusaurus.io/) is a popular documentation website builder. Docusaurus uses React to generate your website UI while Astro supports React, Vue.js, Svelte, and raw HTML templating.
|
||||
|
||||
Docusaurus was designed to build documentation websites and has some built-in, documentation-specific website features that Astro does not. Instead, Astro offers documentation-specific features through an official [`docs`](https://github.com/snowpackjs/astro/tree/main/examples/docs) theme that you can use for your site. This website was built using that template!
|
||||
|
||||
#### Comparing Docusaurus vs. Astro Performance
|
||||
|
||||
In most cases, Astro websites will load significantly faster than Docusaurus websites. This is because Astro automatically strips unnecessary JavaScript from the page, hydrating only the individual components that need it. This feature is called [partial hydration](/core-concepts/component-hydration).
|
||||
|
||||
Docusaurus doesn't support partial hydration, and instead has the user load and rehydrate the entire page in the browser, even if most of the page content is static. This creates a slower page load and worse performance for your website. There is no way to disable this behavior in Docusaurus.
|
||||
|
||||
#### Case Study: Building a Documentation Website
|
||||
|
||||
[docusaurus.io/docs](https://docusaurus.io/docs) is the official Docusaurus documentation website, built with Docusaurus. The website offers a similar enough design and featureset to compare against the official Astro documentation website. This gives us a **_rough, real-world_** comparison between the two site builders.
|
||||
|
||||
- **Docusaurus performance score**: 26 out of 100 [(full audit)](https://lighthouse-dot-webdotdevsite.appspot.com//lh/html?url=https%3A%2F%2Fdocusaurus.io%2Fdocs)
|
||||
- **Astro performance score**: 95 out of 100 [(full audit)](https://lighthouse-dot-webdotdevsite.appspot.com//lh/html?url=https%3A%2F%2Fdocs.astro.build%2Fgetting-started)
|
||||
|
||||
One big reason behind this performance difference is Astro's smaller JavaScript payload: [docusaurus.io/docs](https://docusaurus.io/docs) loads **238kb** of JavaScript on first load while [docs.astro.build](https://docs.astro.build) only loads **9.3kb** (96% less JavaScript, overall).
|
||||
|
||||
## Eleventy vs. Astro
|
||||
|
||||
[Eleventy](https://www.11ty.dev/) is a popular static site builder, powered by Node.js.
|
||||
|
||||
Eleventy uses several [older HTML templating languages](https://www.11ty.dev/docs/languages/) to render your website: Nunjucks, Liquid, Pug, EJS, and others. Astro lets you create pages using your favorite UI component libraries (React, Preact, Vue, Svelte, and others) or a built-in component syntax that is similar to HTML/JSX. Eleventy does not support using modern UI components for HTML templating.
|
||||
|
||||
#### Comparing Eleventy vs. Astro Performance
|
||||
|
||||
Conceptually, Eleventy is aligned with Astro's "minimal client-side JavaScript" approach to web development. Eleventy and Astro both offer similar, zero-JavaScript-by-default performance baselines.
|
||||
|
||||
Eleventy achieves this by pushing you to avoid JavaScript entirely. Eleventy sites are often written with little to no JavaScript at all. This becomes an issue when you do need client-side JavaScript. It is up to you to create your own asset build pipeline for Eleventy. This can be time consuming and forces you to set up bundling, minification, and other complex optimizations yourself.
|
||||
|
||||
By contrast, Astro automatically builds your client-side JavaScript & CSS for you. Astro automatically strips unnecessary JavaScript from the page, hydrating only the individual components that need it. This feature is called [partial hydration](/core-concepts/component-hydration). While it is possible to achieve this yourself in Eleventy, Astro offers it built in by default.
|
||||
|
||||
<!--
|
||||
## Gatsby vs. Astro
|
||||
|
||||
**Next.js** is a popular website & application framework for React.
|
||||
|
||||
|
||||
## Hexo vs. Astro
|
||||
|
||||
**Hexo** is a popular static site generator, powered by Node.js.
|
||||
|
||||
-->
|
||||
|
||||
## Hugo vs. Astro
|
||||
|
||||
[Hugo](https://gohugo.io/) is a popular static site generator, powered by Go.
|
||||
|
||||
Hugo uses a custom [templating language](https://gohugo.io/templates/introduction/) to render your website. Astro lets you create pages using your favorite UI component libraries (React, Preact, Vue, Svelte, and others) or a built-in component syntax that is similar to HTML/JSX. Hugo does not support using modern UI components for HTML templating.
|
||||
|
||||
#### Comparing Hugo vs. Astro Performance
|
||||
|
||||
Conceptually, Hugo is aligned with Astro's "minimal client-side JavaScript" approach to web development. Hugo and Astro both offer similar, zero-JavaScript-by-default performance baselines.
|
||||
|
||||
Both Hugo and Astro offer built-in support for building, bundling and minifying JavaScript. Astro automatically strips unnecessary JavaScript from the page, hydrating only the individual components that need it. This feature is called [partial hydration](/core-concepts/component-hydration). While it is possible to achieve this yourself in Hugo, Astro offers it built in by default.
|
||||
|
||||
## Jekyll vs. Astro
|
||||
|
||||
[Jekyll](https://jekyllrb.com/) is a popular static site generator, powered by Ruby.
|
||||
|
||||
Jekyll uses an older [templating language](https://jekyllrb.com/docs/liquid/) to render your website called Liquid. Astro lets you create pages using your favorite UI component libraries (React, Preact, Vue, Svelte, and others) or a built-in component syntax that is similar to HTML/JSX. Jekyll does not support using modern UI components for HTML templating.
|
||||
|
||||
#### Comparing Jekyll vs. Astro Performance
|
||||
|
||||
Conceptually, Jekyll is aligned with Astro's "minimal client-side JavaScript" approach to web development. Jekyll and Astro both offer similar, zero-JavaScript-by-default performance baselines.
|
||||
|
||||
Jekyll achieves this by pushing you to avoid JavaScript entirely. Jekyll sites are often written with little to no JavaScript at all, and instead promote server-side HTML rendering. This becomes an issue when you do need client-side JavaScript. It is up to you to create your own build pipeline for Jekyll. This can be time-consuming and forces you to set up bundling, minification, and other optimizations yourself.
|
||||
|
||||
By contrast, Astro automatically builds your client-side JavaScript for you. Astro only sends the bare minimum amount of JavaScript to the browser, minified, bundled and optimized for production. While it is possible to achieve this yourself in Jekyll, with Astro this is built in by default.
|
||||
|
||||
## SvelteKit vs. Astro
|
||||
|
||||
[SvelteKit](https://kit.svelte.dev/) is a popular website & application framework for Svelte.
|
||||
|
||||
SvelteKit uses Svelte to render your website. Astro is more flexible: you can use any UI component libraries (React, Preact, Vue, Svelte, and others) or Astro's built-in component syntax that is similar to HTML/JSX.
|
||||
|
||||
Both SvelteKit and Astro are frameworks for building websites. SvelteKit does best with highly dynamic websites (like dashboards and inboxes) while Astro does best with highly static websites (like content and eCommerce websites).
|
||||
|
||||
SvelteKit supports both Static Site Generation (SSG) and Server-Side Rendering (SSR). Today, Astro only supports Static Site Generation (SSG).
|
||||
|
||||
#### Comparing SvelteKit vs. Astro Performance
|
||||
|
||||
In most cases, Astro websites will load faster than SvelteKit websites. This is because Astro automatically strips unnecessary JavaScript from the page, hydrating only the individual components that need it. This feature is called [partial hydration](/core-concepts/component-hydration).
|
||||
|
||||
SvelteKit doesn't support partial hydration, and instead has the user load and rehydrate the entire page in the browser, even if most of the page content is static. This creates a slower page load and worse performance for your website. SvelteKit does offer support for [page-level static, zero-JavaScript pages](https://kit.svelte.dev/docs#ssr-and-javascript-hydrate). However, there is no planned support for hydrating individual components on the page. This leaves you with an all-or-nothing decision for interactivity on each page.
|
||||
|
||||
#### Case Study: Building a Documentation Website
|
||||
|
||||
[kit.svelte.dev](https://kit.svelte.dev/docs#ssr-and-javascript-hydrate) is the official SvelteKit documentation website, built with SvelteKit. The website offers a similar enough design and featureset to compare against the official Astro documentation website. This gives us a **_rough, real-world_** comparison between the two site builders for this common use-case.
|
||||
|
||||
One notable difference between the two sites being tested: SvelteKit's documentation is served as a single page while Astro's is broken up into multiple pages. This larger content payload should have a slight negative impact on performance that is not related to the tool itself.
|
||||
|
||||
- **SvelteKit performance score**: 92 out of 100 [(full audit)](https://lighthouse-dot-webdotdevsite.appspot.com//lh/html?url=https%3A%2F%2Fkit.svelte.dev%2Fdocs)
|
||||
- **Astro performance score**: 95 out of 100 [(full audit)](https://lighthouse-dot-webdotdevsite.appspot.com//lh/html?url=https%3A%2F%2Fdocs.astro.build%2Fgetting-started)
|
||||
|
||||
SvelteKit performed comparably to Astro in this test.
|
||||
|
||||
## Next.js vs. Astro
|
||||
|
||||
[Next.js](https://nextjs.org/) is a popular website & application framework for React.
|
||||
|
||||
Next.js uses React to render your website. Astro is more flexible: you can use any UI component libraries (React, Preact, Vue, Svelte, and others) or Astro's built-in component syntax that is similar to HTML/JSX.
|
||||
|
||||
Both Next.js and Astro are frameworks for building websites. Next.js does best with highly dynamic websites (like dashboards and inboxes) while Astro does best with highly static websites (like content and eCommerce websites).
|
||||
|
||||
Next.js supports both Static Site Generation (SSG) and Server-Side Rendering (SSR). Today, Astro only supports Static Site Generation (SSG).
|
||||
|
||||
#### Comparing Next.js vs. Astro Performance
|
||||
|
||||
In most cases, Astro websites will load significantly faster than Next.js websites. This is because Astro automatically strips unnecessary JavaScript from the page, hydrating only the individual components that need it. This feature is called [partial hydration](/core-concepts/component-hydration).
|
||||
|
||||
Next.js doesn't support partial hydration, and instead has the user load and rehydrate the entire page in the browser, even if most of the page content is static. This creates a slower page load and worse performance for your website. Next.js has [experimental support](https://piccalil.li/blog/new-year-new-website/#heading-no-client-side-react-code) for fully-static, zero-JavaScript pages. However, there is no planned support for hydrating individual components on the page. This leaves you with an all-or-nothing decision for interactivity on each page.
|
||||
|
||||
Next.js has great built-in image optimizations, which could make Next.js a better choice for some image-heavy websites.
|
||||
|
||||
#### Case Study: Building a Documentation Website
|
||||
|
||||
[nextjs.org/docs](https://nextjs.org/docs/getting-started) is the official Next.js documentation website, built with Next.js. The website offers a similar enough design and featureset to compare against the official Astro documentation website. This gives us a **_rough, real-world_** comparison between the two site builders for this common use-case.
|
||||
|
||||
- **Next.js performance score**: 59 out of 100 [(full audit)](https://lighthouse-dot-webdotdevsite.appspot.com//lh/html?url=https%3A%2F%2Fnextjs.org%2Fdocs%2Fgetting-started)
|
||||
- **Astro performance score**: 95 out of 100 [(full audit)](https://lighthouse-dot-webdotdevsite.appspot.com//lh/html?url=https%3A%2F%2Fdocs.astro.build%2Fgetting-started)
|
||||
|
||||
One big reason behind this performance difference is Astro's smaller JavaScript payload: [nextjs.org/docs](https://nextjs.org/docs/getting-started) loads **463kb** of JavaScript on first load while [docs.astro.build](https://docs.astro.build) only loads **9.3kb** (98% less JavaScript, overall).
|
||||
|
||||
## Nuxt vs. Astro
|
||||
|
||||
[Nuxt](https://nextjs.org/) is a popular website & application framework for Vue. It is similar to Next.js.
|
||||
|
||||
Nuxt uses Vue to render your website. Astro is more flexible: you can use any UI component libraries (React, Preact, Vue, Svelte, and others) or Astro's built-in component syntax that is similar to HTML/JSX.
|
||||
|
||||
Both Nuxt and Astro are frameworks for building websites. Nuxt does best with highly dynamic websites (like dashboards and inboxes) while Astro does best with highly static websites (like content and eCommerce websites).
|
||||
|
||||
Nuxt supports both Static Site Generation (SSG) and Server-Side Rendering (SSR). Today, Astro only supports Static Site Generation (SSG).
|
||||
|
||||
#### Comparing Nuxt vs. Astro Performance
|
||||
|
||||
In most cases, Astro websites will load significantly faster than Nuxt websites. This is because Astro automatically strips unnecessary JavaScript from the page, hydrating only the individual components that need it. This feature is called [partial hydration](/core-concepts/component-hydration).
|
||||
|
||||
Nuxt doesn't support partial hydration, and instead has the user load and rehydrate the entire page in the browser, even if most of the page content is static. This creates a slower page load and worse performance for your website. There is no way to disable this behavior in Nuxt.
|
||||
|
||||
Nuxt has great built-in image optimizations, which could make Nuxt a better choice for some image-heavy websites.
|
||||
|
||||
#### Case Study: Building a Documentation Website
|
||||
|
||||
[nuxtjs.org/docs](https://nuxtjs.org/docs/2.x/get-started/installation) is the official Nuxt documentation website, built with Nuxt. The website offers a similar enough design and featureset to compare against the official Astro documentation website. This gives us a **_rough, real-world_** comparison between the two site builders for this common use-case.
|
||||
|
||||
- **Nuxt performance score**: 48 out of 100 [(full audit)](https://lighthouse-dot-webdotdevsite.appspot.com//lh/html?url=https%3A%2F%2Fnuxtjs.org%2Fdocs%2F2.x%2Fget-started%2Finstallation)
|
||||
- **Astro performance score**: 95 out of 100 [(full audit)](https://lighthouse-dot-webdotdevsite.appspot.com//lh/html?url=https%3A%2F%2Fdocs.astro.build%2Fgetting-started)
|
||||
|
||||
One big reason behind this performance difference is Astro's smaller JavaScript payload: [nuxtjs.org/docs](https://nuxtjs.org/docs/2.x/get-started/installation) loads **469kb** of JavaScript on first load while [docs.astro.build](https://docs.astro.build) only loads **9.3kb** (98% less JavaScript, overall).
|
||||
|
||||
## VuePress vs. Astro
|
||||
|
||||
[VuePress](https://vuepress.vuejs.org/guide/) is a popular documentation website builder. VuePress uses Vue.js to generate your website UI while Astro supports React, Vue.js, Svelte, and raw HTML templating.
|
||||
|
||||
VuePress was designed to build documentation websites and has some built-in, documentation-specific website features that Astro does not. Instead, Astro offers documentation-specific features through an official [`docs`](https://github.com/snowpackjs/astro/tree/main/examples/docs) theme that you can use for your site. This website was built using that template!
|
||||
|
||||
#### Comparing VuePress vs. Astro Performance
|
||||
|
||||
In most cases, Astro websites will load significantly faster than VuePress websites. This is because Astro automatically strips unnecessary JavaScript from the page, hydrating only the individual components that need it. This feature is called [partial hydration](/core-concepts/component-hydration).
|
||||
|
||||
VuePress doesn't support partial hydration, and instead has the user load and rehydrate the entire page in the browser, even if most of the page content is static. This creates a slower page load and worse performance for your website. There is no way to disable this behavior in VuePress.
|
||||
|
||||
#### Case Study: Building a Documentation Website
|
||||
|
||||
[vuepress.vuejs.org](https://vuepress.vuejs.org/guide/) is the official VuePress documentation website, built with VuePress. The website offers a similar enough design and featureset to compare against the official Astro documentation website. This gives us a **_rough, real-world_** comparison between the two site builders for this common use-case.
|
||||
|
||||
- **Vuepress performance score**: 63 out of 100 [(full audit)](https://lighthouse-dot-webdotdevsite.appspot.com//lh/html?url=https%3A%2F%2Fvuepress.vuejs.org%2Fguide%2F)
|
||||
- **Astro performance score**: 95 out of 100 [(full audit)](https://lighthouse-dot-webdotdevsite.appspot.com//lh/html?url=https%3A%2F%2Fdocs.astro.build%2Fgetting-started)
|
||||
|
||||
One big reason behind this performance difference is Astro's smaller JavaScript payload: [vuepress.vuejs.org](https://vuepress.vuejs.org/guide/) loads **166kb** of JavaScript on first load while [docs.astro.build](https://docs.astro.build) only loads **9.3kb** (95% less JavaScript, overall).
|
330
docs/src/pages/group-10/core-concepts/astro-components.md
Normal file
330
docs/src/pages/group-10/core-concepts/astro-components.md
Normal file
|
@ -0,0 +1,330 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Astro Components
|
||||
---
|
||||
|
||||
**Astro Components** (files ending with `.astro`) are the foundation of server-side templating in Astro. Think of the Astro component syntax as HTML enhanced with JavaScript.
|
||||
|
||||
Learning a new syntax can feel intimidating, so we carefully designed the Astro component syntax to feel as familiar to web developers as possible. It borrows heavily from patterns you likely already know: components, frontmatter, props, and JSX expressions. We're confident that this guide will have you writing Astro components in no time, especially if you are already familiar with HTML & JavaScript.
|
||||
|
||||
## Syntax Overview
|
||||
|
||||
A single `.astro` file represents a single Astro component in your project. This pattern is known as a **Single-File Component (SFC)**. Both Svelte (`.svelte`) and Vue (`.vue`) also follow this pattern.
|
||||
|
||||
Below is a walk-through of the different pieces and features of the Astro component syntax. You can read it start-to-finish, or jump between sections.
|
||||
|
||||
### HTML Template
|
||||
|
||||
Astro component syntax is a superset of HTML. **If you know HTML, you already know enough to write your first Astro component.**
|
||||
|
||||
For example, this three-line file is a valid Astro component:
|
||||
|
||||
```html
|
||||
<!-- Example1.astro - Static HTML is a valid Astro component! -->
|
||||
<div class="example-1">
|
||||
<h1>Hello world!</h1>
|
||||
</div>
|
||||
```
|
||||
|
||||
An Astro component represents some snippet of HTML in your project. This can be a reusable component, or an entire page of HTML including `<html>`, `<head>` and `<body>` elements. See our guide on [Astro Pages](/core-concepts/astro-pages) to learn how to build your first full HTML page with Astro.
|
||||
|
||||
**Every Astro component must include an HTML template.** While you can enhance your component in several ways (see below), at the end of the day it's the HTML template that dictates what your rendered Astro component will look like.
|
||||
|
||||
### CSS Styles
|
||||
|
||||
CSS rules inside of a `<style>` tag are automatically scoped to that component. That means that you can reuse class names across multiple components, without worrying about conflicts. Styles are automatically extracted and optimized in the final build so that you don't need to worry about style loading.
|
||||
|
||||
For best results, you should only have one `<style>` tag per-Astro component. This isn't necessarily a limitation, but it will often result in better-optimized CSS in your final build. When you're working with pages, the `<style>` tag can go nested inside of your page `<head>`. For standalone components, the `<style>` tag can go at the top-level of your template.
|
||||
|
||||
```html
|
||||
<!-- Astro Component CSS example -->
|
||||
<style>
|
||||
.circle {
|
||||
background-color: red;
|
||||
border-radius: 999px;
|
||||
height: 50px;
|
||||
width: 50px;
|
||||
}
|
||||
</style>
|
||||
<div class="circle"></div>
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- Astro Page CSS example -->
|
||||
<html>
|
||||
<head>
|
||||
<style>
|
||||
...;
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
...
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
Using `<style global>` will skip automatic scoping for every CSS rule in the `<style>` block. This escape hatch should be avoided if possible but can be useful if, for example, you need to modify styling for HTML elements added by an external library.
|
||||
|
||||
Sass (an alternative to CSS) is also available via `<style lang="scss">`.
|
||||
|
||||
📚 Read our full guide on [Component Styling](/guides/styling) to learn more.
|
||||
|
||||
### Frontmatter Script
|
||||
|
||||
To build dynamic components, we introduce the idea of a frontmatter component script. [Frontmatter](https://jekyllrb.com/docs/front-matter/) is a common pattern in Markdown, where some config/metadata is contained inside a code fence (`---`) at the top of the file. Astro does something similar, but with full support for JavaScript & TypeScript in your components.
|
||||
|
||||
Remember that Astro is a server-side templating language, so your component script will run during the build but only the HTML is rendered to the browser. To send JavaScript to the browser, you can use a `<script>` tag in your HTML template or [convert your component to use a frontend framework](/core-concepts/component-hydration) like React, Svelte, Vue, etc.
|
||||
|
||||
```astro
|
||||
---
|
||||
// Anything inside the `---` code fence is your component script.
|
||||
// This JavaScript code runs at build-time.
|
||||
// See below to learn more about what you can do.
|
||||
console.log('This runs at build-time, is visible in the CLI output');
|
||||
// Tip: TypeScript is also supported out-of-the-box!
|
||||
const thisWorks: number = 42;
|
||||
---
|
||||
<div class="example-1">
|
||||
<h1>Hello world!</h1>
|
||||
</div>
|
||||
```
|
||||
|
||||
### Component Imports
|
||||
|
||||
An Astro component can reuse other Astro components inside of its HTML template. This becomes the foundation of our component system: build new components and then reuse them across your project.
|
||||
|
||||
To use an Astro component in your template, you first need to import it in the frontmatter component script. An Astro component is always the file's default import.
|
||||
|
||||
Once imported, you can use it like any other HTML element in your template. Note that an Astro component **MUST** begin with an uppercase letter. Astro will use this to distinguish between native HTML elements (`form`, `input`, etc.) and your custom Astro components.
|
||||
|
||||
```astro
|
||||
---
|
||||
// Import your components in your component script...
|
||||
import SomeComponent from './SomeComponent.astro';
|
||||
---
|
||||
<!-- ... then use them in your HTML! -->
|
||||
<div>
|
||||
<SomeComponent />
|
||||
</div>
|
||||
```
|
||||
|
||||
📚 You can also import and use components from other frontend frameworks like React, Svelte, and Vue. Read our guide on [Component Hydration](/core-concepts/component-hydration) to learn more.
|
||||
|
||||
### Dynamic JSX Expressions
|
||||
|
||||
Instead of inventing our own custom syntax for dynamic templating, we give you direct access to JavaScript values inside of your HTML, using something that feels just like [JSX](https://reactjs.org/docs/introducing-jsx.html).
|
||||
|
||||
Astro components can define local variables inside of the Frontmatter script. Any script variables are then automatically available in the HTML template below.
|
||||
|
||||
#### Dynamic Values
|
||||
|
||||
```astro
|
||||
---
|
||||
const name = "Your name here";
|
||||
---
|
||||
<div>
|
||||
<h1>Hello {name}!</h1>
|
||||
</div>
|
||||
```
|
||||
|
||||
#### Dynamic Attributes
|
||||
|
||||
```astro
|
||||
---
|
||||
const name = "Your name here";
|
||||
---
|
||||
<div>
|
||||
<div data-name={name}>Attribute expressions supported</div>
|
||||
<div data-hint={`Use JS template strings to mix ${"variables"}.`}>So good!</div>
|
||||
</div>
|
||||
```
|
||||
|
||||
#### Dynamic HTML
|
||||
|
||||
```astro
|
||||
---
|
||||
const items = ["Dog", "Cat", "Platipus"];
|
||||
---
|
||||
<ul>
|
||||
{items.map((item) => (
|
||||
<li>{item}</li>
|
||||
))}
|
||||
</ul>
|
||||
```
|
||||
|
||||
### Component Props
|
||||
|
||||
An Astro component can define and accept props. Props are available on the `Astro.props` global in your frontmatter script.
|
||||
|
||||
```astro
|
||||
---
|
||||
// Example: <SomeComponent greeting="(Optional) Hello" name="Required Name" />
|
||||
const { greeting = 'Hello', name } = Astro.props;
|
||||
---
|
||||
<div>
|
||||
<h1>{greeting}, {name}!</h1>
|
||||
</div>
|
||||
```
|
||||
|
||||
You can define your props with TypeScript by exporting a `Props` type interface. In the future, Astro will automatically pick up any exported `Props` interface and give type warnings/errors for your project.
|
||||
|
||||
```astro
|
||||
---
|
||||
// Example: <SomeComponent /> (WARNING: "name" prop is required)
|
||||
export interface Props {
|
||||
name: string;
|
||||
greeting?: string;
|
||||
}
|
||||
const { greeting = 'Hello', name } = Astro.props;
|
||||
---
|
||||
<div>
|
||||
<h1>{greeting}, {name}!</h1>
|
||||
</div>
|
||||
```
|
||||
|
||||
### Slots
|
||||
|
||||
`.astro` files use the [`<slot>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot) tag to enable component composition. Coming from React or Preact, this is the same concept as `children`. You can think of the `<slot>` element as a placeholder for markup which will be passed in from outside of the component.
|
||||
|
||||
```astro
|
||||
<!-- Example: MyComponent.astro -->
|
||||
<div id="my-component">
|
||||
<slot /> <!-- children will go here -->
|
||||
</div>
|
||||
|
||||
<!-- Usage -->
|
||||
<MyComponent>
|
||||
<h1>Hello world!</h1>
|
||||
</MyComponent>
|
||||
```
|
||||
|
||||
Note that if the `<slot>` tag is not used in the HTML template, any children passed to the component will not be rendered.
|
||||
|
||||
Slots become even more powerful when using **named slots**. Rather than a single `<slot>` element which renders _all_ children, named slots allow you to specify multiple places where children should be placed.
|
||||
|
||||
> **Note:** The `slot` attribute is not restricted to plain HTML, components can use `slot` as well!
|
||||
|
||||
```astro
|
||||
<!-- Example: MyComponent.astro -->
|
||||
<div id="my-component">
|
||||
<header>
|
||||
<!-- children with the `slot="header"` attribute will go here -->
|
||||
<slot name="header" />
|
||||
</header>
|
||||
<main>
|
||||
<!-- children without a `slot` (or with the `slot="default"`) attribute will go here -->
|
||||
<slot />
|
||||
</main>
|
||||
<footer>
|
||||
<!-- children with the `slot="footer"` attribute will go here -->
|
||||
<slot name="footer" />
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
<!-- Usage -->
|
||||
<MyComponent>
|
||||
<h1 slot="header">Hello world!</h1>
|
||||
<p>Lorem ipsum ...</p>
|
||||
<FooterComponent slot="footer" />
|
||||
</MyComponent>
|
||||
```
|
||||
|
||||
Slots can also render **fallback content**. When there are no matching children passed to a `<slot>`, a `<slot>` element will render its own placeholder children.
|
||||
|
||||
```astro
|
||||
<!-- MyComponent.astro -->
|
||||
<div id="my-component">
|
||||
<slot>
|
||||
<h1>I will render when this slot does not have any children!</h1>
|
||||
</slot>
|
||||
</div>
|
||||
|
||||
<!-- Usage -->
|
||||
<MyComponent />
|
||||
```
|
||||
|
||||
### Fragments & Multiple Elements
|
||||
|
||||
An Astro component template can render as many top-level elements as you'd like. Unlike other UI component frameworks, you don't need to wrap everything in a single `<div>` if you'd prefer not to.
|
||||
|
||||
```html
|
||||
<!-- An Astro component can contain multiple top-level HTML elements: -->
|
||||
<div id="a" />
|
||||
<div id="b" />
|
||||
<div id="c" />
|
||||
```
|
||||
|
||||
When working inside a JSX expression, however, you must wrap multiple elements inside of a **Fragment**. Fragments let you render a set of elements without adding extra nodes to the DOM. This is required in JSX expressions because of a limitation of JavaScript: You can never `return` more than one thing in a JavaScript function or expression. Using a Fragment solves this problem.
|
||||
|
||||
A Fragment must open with `<>` and close with `</>`. Don't worry if you forget this, Astro's compiler will warn you that you need to add one.
|
||||
|
||||
```astro
|
||||
---
|
||||
const items = ["Dog", "Cat", "Platipus"];
|
||||
---
|
||||
<ul>
|
||||
{items.map((item) => (
|
||||
<>
|
||||
<li>Red {item}</li>
|
||||
<li>Blue {item}</li>
|
||||
<li>Green {item}</li>
|
||||
</>
|
||||
))}
|
||||
</ul>
|
||||
```
|
||||
|
||||
## 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.
|
||||
|
||||
| Feature | Astro | JSX |
|
||||
| ---------------------------- | ------------------------------------------ | -------------------------------------------------- |
|
||||
| File extension | `.astro` | `.jsx` or `.tsx` |
|
||||
| User-Defined Components | `<Capitalized>` | `<Capitalized>` |
|
||||
| Expression Syntax | `{}` | `{}` |
|
||||
| Spread Attributes | `{...props}` | `{...props}` |
|
||||
| Boolean Attributes | `autocomplete` === `autocomplete={true}` | `autocomplete` === `autocomplete={true}` |
|
||||
| Inline Functions | `{items.map(item => <li>{item}</li>)}` | `{items.map(item => <li>{item}</li>)}` |
|
||||
| IDE Support | WIP - [VS Code][code-ext] | Phenomenal |
|
||||
| Requires JS import | No | Yes, `jsxPragma` (`React` or `h`) must be in scope |
|
||||
| Fragments | Automatic top-level, `<>` inside functions | Wrap with `<Fragment>` or `<>` |
|
||||
| Multiple frameworks per-file | Yes | No |
|
||||
| Modifying `<head>` | Just use `<head>` | Per-framework (`<Head>`, `<svelte:head>`, etc) |
|
||||
| Comment Style | `<!-- HTML -->` | `{/* JavaScript */}` |
|
||||
| Special Characters | ` ` | `{'\xa0'}` or `{String.fromCharCode(160)}` |
|
||||
| Attributes | `dash-case` | `camelCase` |
|
||||
|
||||
## URL resolution
|
||||
|
||||
It's important to note that Astro **won't** transform HTML references for you. For example, consider an `<img>` tag with a relative `src` attribute inside `src/pages/about.astro`:
|
||||
|
||||
```html
|
||||
<!-- ❌ Incorrect: will try and load `/about/thumbnail.png` -->
|
||||
<img src="./thumbnail.png" />
|
||||
```
|
||||
|
||||
Since `src/pages/about.astro` will build to `/about/index.html`, you may not have expected that image to live at `/about/thumbnail.png`. So to fix this, choose either of two options:
|
||||
|
||||
#### Option 1: Absolute URLs
|
||||
|
||||
```html
|
||||
<!-- ✅ Correct: references public/thumbnail.png -->
|
||||
<img src="/thumbnail.png" />
|
||||
```
|
||||
|
||||
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
|
||||
|
||||
```astro
|
||||
---
|
||||
// ✅ Correct: references src/thumbnail.png
|
||||
import thumbnailSrc from './thumbnail.png';
|
||||
---
|
||||
|
||||
<img src={thumbnailSrc} />
|
||||
```
|
||||
|
||||
If you'd prefer to organize assets alongside Astro components, you may import the file in JavaScript inside the component script. This works as intended but this makes `thumbnail.png` harder to reference in other parts of your app, as its final URL isn't easily-predictable (unlike assets in `public/*`, where the final URL is guaranteed to never change).
|
||||
|
||||
[code-ext]: https://marketplace.visualstudio.com/items?itemName=astro-build.astro-vscode
|
60
docs/src/pages/group-10/core-concepts/astro-pages.md
Normal file
60
docs/src/pages/group-10/core-concepts/astro-pages.md
Normal file
|
@ -0,0 +1,60 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Pages
|
||||
---
|
||||
|
||||
**Pages** are a special type of [Astro Component](/core-concepts/astro-components) that handle routing, data loading, and templating for each page of your website. You can think of them like any other Astro component, just with extra responsibilities.
|
||||
|
||||
Astro also supports Markdown for content-heavy pages, like blog posts and documentation. See [Markdown Content](/guides/markdown-content) for more information on writing pages with Markdown.
|
||||
|
||||
## File-based Routing
|
||||
|
||||
Astro uses Pages to do something called **file-based routing.** Every file in your `src/pages` directory becomes a page on your site, using the file name to decide the final route.
|
||||
|
||||
Astro Components (`.astro`) and Markdown Files (`.md`) are the only supported formats for pages. Other page types (like a `.jsx` React component) are not supported, but you can use anything as a UI component inside of an `.astro` page to achieve a similar result.
|
||||
|
||||
```
|
||||
src/pages/index.astro -> mysite.com/
|
||||
src/pages/about.astro -> mysite.com/about
|
||||
src/pages/about/index.astro -> mysite.com/about
|
||||
src/pages/about/me.astro -> mysite.com/about/me
|
||||
src/pages/posts/1.md -> mysite.com/posts/1
|
||||
```
|
||||
|
||||
## Page Templating
|
||||
|
||||
All Astro components are responsible for returning HTML. Astro Pages return HTML as well, but have the unique responsibility of returning a full `<html>...</html>` page response, including `<head>` ([MDN<span class="sr-only">- head</span>](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head)) and `<body>` ([MDN<span class="sr-only">- body</span>](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/body)).
|
||||
|
||||
`<!doctype html>` is optional, and will be added automatically.
|
||||
|
||||
```astro
|
||||
---
|
||||
// Example: HTML page skeleton
|
||||
---
|
||||
<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Document title</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Hello, world!</h1>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
## Data Loading
|
||||
|
||||
Astro pages can fetch data to help generate your pages. Astro provides two different tools to pages to help you do this: **fetch()** and **top-level await.**
|
||||
|
||||
📚 Read our [full guide](/guides/data-fetching) on data-fetching to learn more.
|
||||
|
||||
```astro
|
||||
---
|
||||
// Example: Astro component scripts run at build time
|
||||
const response = await fetch('http://example.com/movies.json');
|
||||
const data = await response.json();
|
||||
console.log(data);
|
||||
---
|
||||
<!-- Output the result to the page -->
|
||||
<div>{JSON.stringify(data)}</div>
|
||||
```
|
292
docs/src/pages/group-10/core-concepts/collections.md
Normal file
292
docs/src/pages/group-10/core-concepts/collections.md
Normal file
|
@ -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 */ };
|
||||
}
|
||||
---
|
||||
<!-- Not shown: Page HTML template -->
|
||||
```
|
||||
|
||||
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;
|
||||
---
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>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</title>
|
||||
</head>
|
||||
<body>
|
||||
{posts.data.map((post) => (
|
||||
<h1>{post.title}</h1>
|
||||
<time>{formatDate(post.published_at)}</time>
|
||||
<a href={post.url}>Read Post</a>
|
||||
))}
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
## 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;
|
||||
---
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>Pagination Example: Page Number {posts.page.current}</title>
|
||||
<link rel="canonical" href={posts.url.current} />
|
||||
<link rel="prev" href={posts.url.prev} />
|
||||
<link rel="next" href={posts.url.next} />
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h5>Results {posts.start + 1}–{posts.end + 1} of {posts.total}</h5>
|
||||
</main>
|
||||
<footer>
|
||||
<h4>Page {posts.page.current} / {posts.page.last}</h4>
|
||||
<nav class="nav">
|
||||
<a class="prev" href={posts.url.prev || '#'}>Prev</a>
|
||||
<a class="next" href={posts.url.next || '#'}>Next</a>
|
||||
</nav>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
## 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 <channel>
|
||||
customData: `<language>en-us</language>
|
||||
<itunes:author>The Sunset Explorers</itunes:author>`,
|
||||
// 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: ``<id>${Astro.site}collection/${item.id}</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 `<link>` tags manually in your `<head>` HTML for feed readers and browsers to pick up:
|
||||
|
||||
```html
|
||||
<link
|
||||
rel="alternate"
|
||||
type="application/rss+xml"
|
||||
title="My RSS Feed"
|
||||
href="/feed/podcast.xml"
|
||||
/>
|
||||
```
|
||||
|
||||
### 📚 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)
|
94
docs/src/pages/group-10/core-concepts/component-hydration.md
Normal file
94
docs/src/pages/group-10/core-concepts/component-hydration.md
Normal file
|
@ -0,0 +1,94 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Partial Hydration in Astro
|
||||
---
|
||||
|
||||
**Astro generates every website with zero client-side JavaScript, by default.** Use any frontend UI component that you'd like (React, Svelte, Vue, etc.) and Astro will automatically render it to HTML at build-time and strip away all JavaScript. This keeps every site fast by default.
|
||||
|
||||
But sometimes, client-side JavaScript is required. This guide shows how interactive components work in Astro using a technique called partial hydration.
|
||||
|
||||
```astro
|
||||
---
|
||||
// Example: Importing and then using a React component.
|
||||
// By default, Astro renders this to HTML and CSS during
|
||||
// your build, with no client-side JavaScript.
|
||||
// (Need client-side JavaScript? Read on...)
|
||||
import MyReactComponent from '../components/MyReactComponent.jsx';
|
||||
---
|
||||
<!-- 100% HTML, Zero JavaScript! -->
|
||||
<MyReactComponent />
|
||||
```
|
||||
|
||||
## Concept: Partial Hydration
|
||||
|
||||
There are plenty of cases where you need an interactive UI component to run in the browser:
|
||||
|
||||
- An image carousel
|
||||
- An auto-complete search bar
|
||||
- A mobile sidebar open/close button
|
||||
- A "Buy Now" button
|
||||
|
||||
In Astro, it's up to you as the developer to explicitly "opt-in" any components on the page that need to run in the browser. Astro can then use this info to know exactly what JavaScript is needed, and only hydrate exactly what's needed on the page. This technique is known as partial hydration.
|
||||
|
||||
**Partial hydration** -- the act of only hydrating the individual components that require JavaScript and leaving the rest of your site as static HTML -- may sound relatively straightforward. It should! Websites have been built this way for decades. It was only recently that Single-Page Applications (SPAs) introduced the idea that your entire website is written in JavaScript and compiled/rendered by every user in the browser.
|
||||
|
||||
_Note: Partial hydration is sometimes called "progressive enhancement" or "progressive hydration." While there are slight nuances between the terms, for our purposes you can think of these all as synonyms of the same concept._
|
||||
|
||||
**Partial hydration is the secret to Astro's fast-by-default performance story.** Next.js, Gatsby, and other JavaScript frameworks cannot support partial hydration because they imagine your entire website/page as a single JavaScript application.
|
||||
|
||||
## Concept: Island Architecture
|
||||
|
||||
**Island architecture** is the idea of using partial hydration to build entire websites. Island architecture is an alternative to the popular idea of building your website into a client-side JavaScript bundle that must be shipped to the user.
|
||||
|
||||
To quote Jason Miller, who [coined the phrase](https://jasonformat.com/islands-architecture/):
|
||||
|
||||
> In an "islands" model, server rendering is not a bolt-on optimization aimed at improving SEO or UX. Instead, it is a fundamental part of how pages are delivered to the browser. The HTML returned in response to navigation contains a meaningful and immediately renderable representation of the content the user requested.
|
||||
|
||||
Besides the obvious performance benefits of sending less JavaScript down to the browser, there are two key benefits to island architecture:
|
||||
|
||||
- **Components load individually.** A lightweight component (like a sidebar toggle) will load and render quickly without being blocked by the heavier components on the page.
|
||||
- **Components render in isolation.** Each part of the page is an isolated unit, and a performance issue in one unit won't directly affect the others.
|
||||
|
||||
![diagram](https://res.cloudinary.com/wedding-website/image/upload/v1596766231/islands-architecture-1.png)
|
||||
|
||||
## Hydrate Interactive Components
|
||||
|
||||
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
|
||||
---
|
||||
// Example: hydrating a React component in the browser.
|
||||
import MyReactComponent from '../components/MyReactComponent.jsx';
|
||||
---
|
||||
<!-- "client:visible" means the component won't load any client-side
|
||||
JavaScript until it becomes visible in the user's browser. -->
|
||||
<MyReactComponent client:visible />
|
||||
```
|
||||
|
||||
### `<MyComponent client:load />`
|
||||
|
||||
Hydrate the component on page load.
|
||||
|
||||
### `<MyComponent client:idle />`
|
||||
|
||||
Hydrate the component as soon as main thread is free (uses [requestIdleCallback()][mdn-ric]).
|
||||
|
||||
### `<MyComponent client:visible />`
|
||||
|
||||
Hydrate the component as soon as the element enters the viewport (uses [IntersectionObserver][mdn-io]). Useful for content lower down on the page.
|
||||
|
||||
### `<MyComponent client:media={QUERY} />`
|
||||
|
||||
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.
|
||||
|
||||
## 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.
|
||||
|
||||
To make your Astro component interactive, you will need to convert it to the frontend framework of your choice: React, Svelte, Vue, etc. If you have no preference, we recommend React or Preact as they are most similar to Astro's syntax.
|
||||
|
||||
Alternatively, you could add a `<script>` tag to your Astro component HTML template and send JavaScript to the browser that way. While this is fine for the simple stuff, we recommend a frontend framework for more complex interactive components.
|
||||
|
||||
[mdn-io]: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API
|
||||
[mdn-ric]: https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback
|
||||
[mdn-mm]: https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia
|
154
docs/src/pages/group-10/core-concepts/layouts.md
Normal file
154
docs/src/pages/group-10/core-concepts/layouts.md
Normal file
|
@ -0,0 +1,154 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Layouts
|
||||
---
|
||||
|
||||
**Layouts** are a special type of [Component](/core-concepts/astro-components) that help you share and reuse common page layouts within your project.
|
||||
|
||||
Layouts are just like any other reusable Astro component. There's no new syntax or APIs to learn. However, reusable page layouts are such a common pattern in web development that we created this guide to help you use them.
|
||||
|
||||
## Usage
|
||||
|
||||
Astro layouts support props, slots, and all of the other features of Astro components. Layouts are just normal components, after all!
|
||||
|
||||
Unlike other components, layouts will often contain the full page `<html>`, `<head>` and `<body>` (often referred to as the **page shell**).
|
||||
|
||||
It's a common pattern to put all of your layout components in a single `src/layouts` directory.
|
||||
|
||||
## Example
|
||||
|
||||
```astro
|
||||
---
|
||||
// src/layouts/BaseLayout.astro
|
||||
const {title} = Astro.props;
|
||||
---
|
||||
<html>
|
||||
<head>
|
||||
<title>Example Layout: {title}</title>
|
||||
</head>
|
||||
<body>
|
||||
<!-- Adds a navigation bar to every page. -->
|
||||
<nav>
|
||||
<a href="#">Home</a>
|
||||
<a href="#">Posts</a>
|
||||
<a href="#">Contact</a>
|
||||
</nav>
|
||||
<!-- slot: your page content will be injected here. -->
|
||||
<slot />
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
📚 The `<slot />` element lets Astro components define where any children elements (passed to the layout) should go. Learn more about how `<slot/>` works in our [Astro Component guide.](/core-concepts/astro-components)
|
||||
|
||||
Once you have your first layout, you can use it like you would any other component on your page. Remember that your layout contains your page `<html>`, `<head>`, and `<body>`. You only need to provide the custom page content.
|
||||
|
||||
```astro
|
||||
---
|
||||
// src/pages/index.astro
|
||||
import BaseLayout from '../layouts/BaseLayout.astro'
|
||||
---
|
||||
<BaseLayout title="Homepage">
|
||||
<h1>Hello, world!</h1>
|
||||
<p>This is my page content. It will be nested inside a layout.</p>
|
||||
</BaseLayout>
|
||||
```
|
||||
|
||||
## Nesting Layouts
|
||||
|
||||
You can nest layouts when you want to create more specific page types without copy-pasting. It is common in Astro to have one generic `BaseLayout` and then many more specific layouts (`PostLayout`, `ProductLayout`, etc.) that reuse and build on top of it.
|
||||
|
||||
```astro
|
||||
---
|
||||
// src/layouts/PostLayout.astro
|
||||
import BaseLayout from '../layouts/BaseLayout.astro'
|
||||
const {title, author} = Astro.props;
|
||||
---
|
||||
<!-- This layout reuses BaseLayout (see example above): -->
|
||||
<BaseLayout title={title}>
|
||||
<!-- Adds new post-specific content to every page. -->
|
||||
<div>Post author: {author}</div>
|
||||
<!-- slot: your page content will be injected here. -->
|
||||
<slot />
|
||||
</BaseLayout>
|
||||
```
|
||||
|
||||
## Composing Layouts
|
||||
|
||||
Sometimes, you need more granular control over your page. For instance, you may want to add SEO or social `meta` tags on some pages, but not others. You could implement this with a prop on your layout (`<BaseLayout addMeta={true} ...`) but at some point it may be easier to compose your layouts without nesting.
|
||||
|
||||
Instead of defining your entire `<html>` page as one big layout, you can define the `head` and `body` contents as smaller, separate components. This lets you compose multiple layouts together in unique ways on every page.
|
||||
|
||||
```astro
|
||||
---
|
||||
// src/layouts/BaseHead.astro
|
||||
const {title, description} = Astro.props;
|
||||
---
|
||||
<meta charset="UTF-8">
|
||||
<title>{title}</title>
|
||||
<meta name="description" content={description}>
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com">
|
||||
<link href="https://fonts.googleapis.com/css2?family=Spectral:ital,wght@0,400;0,700;1,400;1,700&display=swap" rel="stylesheet">
|
||||
```
|
||||
|
||||
Notice how this layout doesn't include your page shell, and only includes some generic elements that should go in your `<head>`. This lets you combine multiple layout components together with more control over the overall page structure.
|
||||
|
||||
```astro
|
||||
---
|
||||
// src/pages/index.astro
|
||||
import BaseHead from '../layouts/BaseHead.astro';
|
||||
import OpenGraphMeta from '../layouts/OpenGraphMeta.astro';
|
||||
---
|
||||
<html>
|
||||
<head>
|
||||
<!-- Now, you have complete control over the head, per-page. -->
|
||||
<BaseHead title="Page Title" description="Page Description" />
|
||||
<OpenGraphMeta />
|
||||
<!-- You can even add custom, one-off elements as needed. -->
|
||||
<link rel="alternate" type="application/rss+xml" href="/feed/posts.xml">
|
||||
</head>
|
||||
<body>
|
||||
<!-- ... -->
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
The one downside to this approach is that you'll need to define the `<html>`, `<head>`, and `<body>` elements on every page yourself. This is needed to construct the page because the layout components no longer contain the full page shell.
|
||||
|
||||
## Markdown Layouts
|
||||
|
||||
Layouts are essential for Markdown files. Markdown files can declare a layout in the file frontmatter. Each Markdown file will be rendered to HTML and then injected into the layout's `<slot />` location.
|
||||
|
||||
```markdown
|
||||
---
|
||||
title: Blog Post
|
||||
layout: ../layouts/PostLayout.astro
|
||||
---
|
||||
|
||||
This blog post will be **rendered** inside of the `<PostLayout />` layout.
|
||||
```
|
||||
|
||||
Markdown pages always pass a `content` prop to their layout, which is useful to grab information about the page, title, metadata, table of contents headers, and more.
|
||||
|
||||
```astro
|
||||
---
|
||||
// src/layouts/PostLayout.astro
|
||||
const { content } = Astro.props;
|
||||
---
|
||||
<html>
|
||||
<head>
|
||||
<title>{content.title}</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>{content.title}</h1>
|
||||
<h2>{content.description}</h2>
|
||||
<img src={content.image} alt="">
|
||||
<article>
|
||||
<!-- slot: Markdown content goes here! -->
|
||||
<slot />
|
||||
</article>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
📚 Learn more about Astro's markdown support in our [Markdown guide](/guides/markdown-content).
|
57
docs/src/pages/group-10/core-concepts/project-structure.md
Normal file
57
docs/src/pages/group-10/core-concepts/project-structure.md
Normal file
|
@ -0,0 +1,57 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Project Structure
|
||||
---
|
||||
|
||||
Astro includes an opinionated folder layout for your project. Every Astro project must include these directories and files:
|
||||
|
||||
- `src/*` - Your project source code (components, pages, etc.)
|
||||
- `public/*` - Your non-code assets (fonts, icons, etc.)
|
||||
- `package.json` - A project manifest.
|
||||
|
||||
The easiest way to set up your new project is with `npm init astro`. Check out our [Installation Guide](/quick-start) for a walkthrough of how to set up your project automatically (with `npm init astro`) or manually.
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
├── src/
|
||||
│ ├── components/
|
||||
│ ├── layouts/
|
||||
│ └── pages/
|
||||
│ └── index.astro
|
||||
├── public/
|
||||
└── package.json
|
||||
```
|
||||
|
||||
### `src/`
|
||||
|
||||
The src folder is where most of your project source code lives. This includes:
|
||||
|
||||
- [Astro Components](/core-concepts/astro-components)
|
||||
- [Pages](/core-concepts/astro-pages)
|
||||
- [Layouts](/core-concepts/layouts)
|
||||
- [Frontend JS Components](/core-concepts/component-hydration)
|
||||
- [Styling (CSS, Sass)](/guides/styling)
|
||||
- [Markdown](/guides/markdown-content)
|
||||
|
||||
Astro has complete control over how these files get processed, optimized, and bundled in your final site build. Some files (like Astro components) never make it to the browser directly and are instead rendered to HTML. Other files (like CSS) are sent to the browser but may be bundled with other CSS files depending on how your site uses them.
|
||||
|
||||
### `src/components`
|
||||
|
||||
[Components](/core-concepts/astro-components) are reusable units of UI for your HTML pages. It is recommended (but not required) that you put your components in this directory. How you organize them within this directory is up to you.
|
||||
|
||||
Your non-Astro UI components (React, Preact, Svelte, Vue, etc.) can also live in the `src/components` directory. Astro will automatically render all components to HTML unless you've enabled a frontend component via partial hydration.
|
||||
|
||||
### `src/layouts`
|
||||
|
||||
[Layouts](/core-concepts/layouts) are reusable components for HTML page layouts. It is recommended (but not required) that you put your layout components in this directory. How you organize them within this directory is up to you.
|
||||
|
||||
### `src/pages`
|
||||
|
||||
[Pages](/core-concepts/astro-pages) contain all pages (`.astro` and `.md` supported) for your website. It is **required** that you put your pages in this directory.
|
||||
|
||||
### `public/`
|
||||
|
||||
For most users, the majority of your files will live inside of the `src/` directory so that Astro can properly handle and optimize them in your final build. By contrast, the `public/` directory is the place for any files to live outside of the Astro build process.
|
||||
|
||||
If you put a file into the public folder, it will not be processed by Astro. Instead it will be copied into the build folder untouched. This can be useful for assets like images and fonts, or when you need to include a specific file like `robots.txt` or `manifest.webmanifest`.
|
69
docs/src/pages/group-10/de/getting-started.md
Normal file
69
docs/src/pages/group-10/de/getting-started.md
Normal file
|
@ -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 `<Markdown />` und `<Prism />`.
|
||||
|
||||
### 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/).
|
62
docs/src/pages/group-10/es/getting-started.md
Normal file
62
docs/src/pages/group-10/es/getting-started.md
Normal file
|
@ -0,0 +1,62 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Empezando
|
||||
lang: es
|
||||
---
|
||||
|
||||
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.
|
||||
|
||||
## Intenta 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 [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
|
||||
|
||||
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 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 el sintaxis de `.astro`
|
||||
|
||||
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 API
|
||||
|
||||
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 `<Markdown/>` y `<Prism/>`.
|
||||
|
||||
### 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
|
||||
|
||||
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 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.
|
||||
|
||||
## ¿Algo Falta?
|
||||
|
||||
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édito
|
||||
|
||||
Esta guía de **Empezando** se basó originalmente en la guía de Empezando de [React](https://reactjs.org/).
|
|
@ -1,9 +1,8 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: 範例
|
||||
lang: zh-Hant-TW
|
||||
title: Examples
|
||||
---
|
||||
|
||||
如果喜歡從做中學,可以看看放在 Github 的[範例資源庫](https://github.com/snowpackjs/astro/tree/main/examples)。
|
||||
If you prefer to learn by example, check out our [Examples Library](https://github.com/snowpackjs/astro/tree/main/examples) on GitHub.
|
||||
|
||||
<!-- Once we merge astro-docs back into the main repo, we can actually fetch the list of examples at build-time by scanning the examples/ directory! -->
|
60
docs/src/pages/group-10/fi/getting-started.md
Normal file
60
docs/src/pages/group-10/fi/getting-started.md
Normal file
|
@ -0,0 +1,60 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Aloittaminen
|
||||
lang: fi
|
||||
---
|
||||
|
||||
Astro on moderni työkalu staattisten sivustojen luomiseen. Voit löytää lisätietoa Astrosta englanniksi [kotisivultamme](https://astro.build/) tai [julkistusviestistämme](https://astro.build/blog/introducing-astro). Tämä sivu on yleiskatsaus Astron dokumentaatioon ja liittyviin sisältöihin.
|
||||
|
||||
Haluatko nähdä nopean yleiskatsauksen siitä mikä Astro on? [Tutustu kotisivuumme.](https://astro.build)
|
||||
|
||||
## Kokeile Astroa
|
||||
|
||||
Helpoin tapa kokeilla Astroa on suorittaa `npm init astro` uudessa hakemistossa omalla koneellasi. Tämä CLI-komento käy lävitse tarvittavat vaiheet uuden Astro-projektin alkuunsaattamiseksi.
|
||||
|
||||
[Asennusoppaastamme](/installation) löydät täyden läpikäynnin Astron saamiseksi käyttökuntoon.
|
||||
|
||||
### Netin leikkikentät
|
||||
|
||||
Sikäli jos sinua kiinnostaa kokeilla Astroa selaimessa, voit käyttää leikkikenttää netissä. Kokeile Hello World -templaattia [CodeSandboxissa](https://codesandbox.io/s/astro-template-hugb3).
|
||||
|
||||
_Huomaa: jotkin toiminnallisuudet (mm. nopea päivitys) ovat toistaiseksi rajallisia CodeSandboxissa._
|
||||
|
||||
## Astron oppiminen
|
||||
|
||||
Ihmisillä on monenlaisia taustoja ja erilaisia oppimistyylejä. Toivomme sinun saavan irti tästä osiosta riippumatta siitä oletko enemmän teoriatason vaiko käytännön tason oppija.
|
||||
|
||||
- Jos suosit **oppimista tekemällä**, kokeile aloittaa [esimerkkikirjastostamme](https://github.com/snowpackjs/astro/tree/main/examples).
|
||||
- Jos suosit **konseptien oppimista vaihe vaiheelta**, kokeile aloittaa [peruskonsepteista ja oppaista](/core-concepts/project-structure).
|
||||
|
||||
Astrolla on oma oppimiskäyränsä kuten millä tahansa ennestään tuntemattomalla teknologialla. Harjoittelulla ja kärsivällisyydellä _tulet_ pääsemään asioista kärryille.
|
||||
|
||||
### `.astro`-syntaksin oppiminen
|
||||
|
||||
Aloittaessasi Astrolla tulet kohtaamaan monia `.astro`-päätteellisiä tiedostoja. Nämä sisältävät **Astro-komponenttien syntaksia**, joka on erityistä HTML:n kaltaista templaattikieltä, jota Astro käyttää. Se on suunniteltu olemaan tuttu kenelle tahansa, jolla on kokemusta HTML:stä tai JSX:stä.
|
||||
|
||||
Oppaamme [Astron komponenteista](/core-concepts/astro-components) esittelee uuden syntaksin ja on paras paikka sen opiskelulle.
|
||||
|
||||
### 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 `<Markdown />` ja `<Prism />`.
|
||||
|
||||
### Dokumentaation versioinnista
|
||||
|
||||
Tämä dokumentaatio edustaa aina Astron viimeisintä vakaata versiota. Saavutettuamme v1.0 virstanpylvään tulemme lisäämään mahdollisuuden tarkastella versioitua dokumentaatiota.
|
||||
|
||||
## Pysyminen ajantasalla
|
||||
|
||||
Twitterin [@astrodotbuild](https://twitter.com/astrodotbuild)-tunnus on virallinen lähde Astro-tiimin päivityksille.
|
||||
|
||||
Tulemme kertomaan julkaisuista myös [Discord-yhteisössä](https://astro.build/chat) kanavalla #announcements.
|
||||
|
||||
Kaikki Astro-julkaisut eivät tule olemaan oman blogikirjoituksensa arvoisia, mutta löydät yksityiskohtaisen muutoslokin jokaiselle julkaisulle [`CHANGELOG.md`-tiedostosta Astron repossa](https://github.com/snowpackjs/astro/blob/main/packages/astro/CHANGELOG.md).
|
||||
|
||||
## Puuttuuko jotakin?
|
||||
|
||||
Mikäli havaitset puutteita dokumentaatiossa tai että osa siitä ovat hämmentäviä, jätäthän [ilmoituksen dokumentaation ongelmasta](https://github.com/snowpackjs/astro/issues/new/choose) sisältäen ehdotuksesi sen parantamiseksi, tai twiittaa [@astrodotbuild](https://twitter.com/astrodotbuild) Twitter-tunnukselle. Otamme palautetta vastaan mielellämme!
|
||||
|
||||
## Kiitokset
|
||||
|
||||
Tämä aloittamisen opas perustui alkujaan [Reactin](https://reactjs.org/) vastaavaan oppaaseen.
|
93
docs/src/pages/group-10/fi/installation.md
Normal file
93
docs/src/pages/group-10/fi/installation.md
Normal file
|
@ -0,0 +1,93 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Asennus
|
||||
lang: fi
|
||||
---
|
||||
|
||||
Astron voi asentaa parilla eri tavalla uuteen projektiin.
|
||||
|
||||
## Vaatimukset
|
||||
|
||||
- **Node.js** - `v12.20.0`, `v14.13.1`, `v16.0.0` tai uudempi.
|
||||
- **Tekstieditori** - Suosittelemme [VS Codea](https://code.visualstudio.com/) yhdessä [Astro-laajennoksen](https://marketplace.visualstudio.com/items?itemName=astro-build.astro-vscode) kanssa.
|
||||
- **Terminaali** - Astroa käytetään pääasiassa komentorivin kautta.
|
||||
|
||||
## Suositeltu asennus
|
||||
|
||||
`npm init astro` on helpoin tapa lisätä Astro uuteen projektiin. Komennon suorittaminen terminaalissa aloittaa `create-astro`-asennusvelhon, joka käy lävitse uuden projektin aloituksen.
|
||||
|
||||
```bash
|
||||
mkdir <projektin-nimi>
|
||||
cd <projektin-nimi>
|
||||
npm init astro
|
||||
```
|
||||
|
||||
Seuraa CLI-ohjelman ohjeistusta asentaaksesi Astron käyttäen yhtä virallisista aloitustemplaateista.
|
||||
|
||||
Tämän jälkeen voit siirtyä [pika-aloitusoppaaseen](/quick-start#start-your-project) saadaksesi 30:n sekunnin yhteenvedon siitä, kuinka käynnistää uusi projekti kehittämistä varten, ja kuinka luoda siitä lopullinen sivusto!
|
||||
|
||||
## Asentaminen itse
|
||||
|
||||
### Projektin valmistelu
|
||||
|
||||
Luo uusi tyhjä hakemisto jolla on projektisi nimi ja siirry siihen:
|
||||
|
||||
```bash
|
||||
mkdir <projektin-nimi>
|
||||
cd <projektin-nimi>
|
||||
# Huomaa: korvaa <projektin-nimi> projektisi nimellä.
|
||||
```
|
||||
|
||||
Luo uusi `package.json`-tiedosto projektille. Astro on suunniteltu toimimaan npm-ympäristössä, jota hallinnoidaan `package.json` sisältämien sääntöjen kautta. Mikäli `package.json` ei ole ennestään tuttu, niin suosittelemme tutustumaan [npm:n dokumentaatioon](https://docs.npmjs.com/creating-a-package-json-file).
|
||||
|
||||
```bash
|
||||
# Tämä komento luo uuden package.json-tiedoston sisältäen muutaman peruskentän
|
||||
npm init --yes
|
||||
```
|
||||
|
||||
### Asenna Astro
|
||||
|
||||
Sinulla tulisi olla nyt hakemisto, josta löytyy yksittäinen `package.json`-tiedosto kun aiemmin mainitut toimet on tehty. Astron lisääminen projektiin on nyt mahdollista.
|
||||
|
||||
Käytämme `npm`:ää esimerkeissämme, mutta vaihtoehtoisesti voit myös käyttää `yarn`:ia tai `pnpm`:ää. Sikäli jos kumpikaan `yarn` tahi `pnpm` ei ole tuttu, niin suosittelemme pitäytymistä `npm`:ssä.
|
||||
|
||||
```bash
|
||||
npm install astro
|
||||
```
|
||||
|
||||
Voit nyt vaihtaa oletuksena toimivan "scripts"-osion `npm init`in luomassa `package.json`:ssa seuraavasti:
|
||||
|
||||
```diff
|
||||
"scripts": {
|
||||
- "test": "echo \"Error: no test specified\" && exit 1"
|
||||
+ "start": "astro dev",
|
||||
+ "build": "astro build"
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Lisää ensimmäinen sivu
|
||||
|
||||
Avaa tekstieditori ja luo uusi tiedosto projektiin:
|
||||
|
||||
```astro
|
||||
---
|
||||
// 1. Luo uusi tiedosto <projektin-hakemisto>/src/pages/index.astro
|
||||
// 2. Kopioi ja liitä tämä koko tiedosto (sisältäen `-` väliviivat) siihen.
|
||||
---
|
||||
<html lang="fi">
|
||||
<body>
|
||||
<h1>Moi maailma!</h1>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
Voit nyt lisätä uusia sivuja `src/pages`-hakemistoon Astron käyttäessä ennettua tiedostonimeä luodakseen uusia sivuja sivustolle. Jos esimerkiksi luot uuden tiedoston nimellä `src/pages/about.astro` (käyttäen edellistä koodia), niin Astro luo uuden sivun osoitteeseen `/about`.
|
||||
|
||||
### Seuraavat vaiheet
|
||||
|
||||
Näin se hoituu! Olet nyt valmis aloittamaan kehittämisen! Siirry [pika-aloitusoppaaseen](/quick-start#start-your-project) saadaksesi 30:n sekunnin läpikäynnin Astron käynnistämisestä ja projektin luomisesta sivustoksi!
|
||||
|
||||
📚 Opi lisää Astron projektien rakenteesta [projektin rakenneoppaassa](/core-concepts/project-structure).
|
||||
📚 Opi lisää Astron komponenttien syntaksista [Astro-komponenttien oppaassa](/core-concepts/astro-components).
|
||||
📚 Opi lisää Astron tiedostoihin pohjautuvasta reitityksestä [reititysoppaassa](core-concepts/astro-pages).
|
51
docs/src/pages/group-10/fi/quick-start.md
Normal file
51
docs/src/pages/group-10/fi/quick-start.md
Normal file
|
@ -0,0 +1,51 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Pika-aloitus
|
||||
lang: fi
|
||||
---
|
||||
|
||||
```shell
|
||||
# vaatimukset: varmista että Node.js on vähintään versiota 12.20.0+, 14.13.1+ tai 16+
|
||||
node --version
|
||||
|
||||
# luo uuden projektin hakemisto ja siirry siihen
|
||||
mkdir astrokokeilu && cd "$_"
|
||||
|
||||
# valmistaudu laukaisuun...
|
||||
npm init astro
|
||||
|
||||
# asenna riippuvuudet
|
||||
npm install
|
||||
|
||||
# aloita kehittäminen!
|
||||
npm start
|
||||
|
||||
# kun olet valmis: luo oma staattinen sivustosi hakemistoon `dist/`
|
||||
npm run build
|
||||
```
|
||||
|
||||
Astro-sivuston käyttöönotto tuotannossa vaatii `/dist`-hakemiston (joka luodaan suorittamalla `npm run build`) sisällön siirtämisen haluamallesi palveluntarjoajalle.
|
||||
|
||||
[Luo lisää tästä Astron julkaisuoppaassa.](/guides/deploy)
|
||||
|
||||
## Projektin käynnistäminen
|
||||
|
||||
Siirry takaisin komentoriville ja suorita tämä komento projektin hakemistossa:
|
||||
|
||||
```bash
|
||||
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.
|
||||
|
||||
Astro seuraa muutoksia `src/`-hakemiston sisällä, joten ohjelmaa ei tarvitse käynnistää uudelleen tehdessäsi muutoksia siihen koodatessasi.
|
||||
|
||||
## Sivuston luominen
|
||||
|
||||
Palaa takaisin komentoriville ja suorita tämä komento projektin hakemistossa:
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
Tämä muodostaa projektista valmiit sivuston tiedostot ja kirjoittaa ne `dist/`-hakemistoon. Astro-sivustot ovat staattisia, joten ne voi julkaista mille tahansa palveluntarjoajalle (Vercel, Netlify, S3 bucket, jne.).
|
61
docs/src/pages/group-10/getting-started.md
Normal file
61
docs/src/pages/group-10/getting-started.md
Normal file
|
@ -0,0 +1,61 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Getting Started
|
||||
---
|
||||
|
||||
Astro is a modern static site builder. Learn what Astro is all about from [our homepage](https://astro.build/) or [our release post](https://astro.build/blog/introducing-astro). This page is an overview of the Astro documentation and all related resources.
|
||||
|
||||
Looking for a quick overview of what Astro is? [Visit our homepage.](https://astro.build)
|
||||
|
||||
## Try Astro
|
||||
|
||||
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 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.
|
||||
|
||||
### Online Playgrounds
|
||||
|
||||
If you're interested in playing around with Astro in the browser, you can use an online code playground. Try our "Hello World!" template on [CodeSandbox](https://codesandbox.io/s/astro-template-hugb3).
|
||||
|
||||
_Note: some features (ex: Fast Refresh) are currently limited on CodeSandbox._
|
||||
|
||||
## Learn Astro
|
||||
|
||||
All manner of people come to Astro from different backgrounds bringing with them different learning styles. Whether you prefer a more theoretical or a practical approach, we hope you'll find this section helpful.
|
||||
|
||||
- If you prefer to **learn by doing**, start with our [examples library](https://github.com/snowpackjs/astro/tree/main/examples).
|
||||
- If you prefer to **learn concepts step by step**, start with our [basic concepts and guides](/core-concepts/project-structure).
|
||||
|
||||
Like any unfamiliar technology, Astro comes with a slight learning curve. However, with practice and some patience, we know, you _will_ get the hang of it, in no time.
|
||||
|
||||
### Learn `.astro` Syntax
|
||||
|
||||
When you begin to learn Astro, you'll see many files using the `.astro` file extension. This is **Astro's Component Syntax**: a special HTML-like file format which Astro uses for templating. It was designed to feel familiar to anyone with HTML or JSX experience.
|
||||
|
||||
Our helpful guide on [Astro components](/core-concepts/astro-components) introduces you to the Astro syntax, and is the best way to learn.
|
||||
|
||||
### 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 `<Markdown />` and `<Prism />`.
|
||||
|
||||
### Versioned Documentation
|
||||
|
||||
This documentation always reflects the latest stable version of Astro. Once we hit the v1.0 milestone, we will add the ability to view versioned documentation.
|
||||
|
||||
## Staying Informed
|
||||
|
||||
The [@astrodotbuild](https://twitter.com/astrodotbuild) Twitter account is the official source for the updates from the Astro team.
|
||||
|
||||
We also post release announcements to our [Discord community](https://astro.build/chat) in the #announcements channel.
|
||||
|
||||
Not every Astro release deserves its own blog post, but you can find a detailed changelog for every release in the [`CHANGELOG.md` file in the Astro repository](https://github.com/snowpackjs/astro/blob/main/packages/astro/CHANGELOG.md).
|
||||
|
||||
## Something Missing?
|
||||
|
||||
If something is missing in the documentation or if you found some part confusing, please [file an issue for the documentation](https://github.com/snowpackjs/astro/issues/new/choose) with your suggestions for improvement, or tweet at the [@astrodotbuild](https://twitter.com/astrodotbuild) Twitter account. We love hearing from you!
|
||||
|
||||
## Credit
|
||||
|
||||
This getting started guide was originally based off of [React's](https://reactjs.org/) getting started guide.
|
64
docs/src/pages/group-10/guides/data-fetching.md
Normal file
64
docs/src/pages/group-10/guides/data-fetching.md
Normal file
|
@ -0,0 +1,64 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Data Fetching
|
||||
---
|
||||
|
||||
Astro components and pages can fetch remote data to help generate your pages. Astro provides two different tools to pages to help you do this: **fetch()** and **top-level await.**
|
||||
|
||||
## `fetch()`
|
||||
|
||||
Astro pages have access to the global `fetch()` function in their setup script. `fetch()` is a native JavaScript API ([MDN<span class="sr-only">- fetch</span>](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)) that lets you make HTTP requests for things like APIs and resources.
|
||||
|
||||
Even though Astro component scripts run inside of Node.js (and not in the browser) Astro provides this native API so that you can fetch data at page build time.
|
||||
|
||||
```astro
|
||||
---
|
||||
// Movies.astro
|
||||
const response = await fetch('https://example.com/movies.json');
|
||||
const data = await response.json();
|
||||
// Remember: Astro component scripts log to the CLI
|
||||
console.log(data);
|
||||
---
|
||||
<!-- Output the result to the page -->
|
||||
<div>{JSON.stringify(data)}</div>
|
||||
```
|
||||
|
||||
## Top-level await
|
||||
|
||||
`await` is another native JavaScript feature that lets you await the response of some asynchronous promise ([MDN<span class="sr-only">- await</span>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await)). Astro supports `await` in the top-level of your component script.
|
||||
|
||||
**Important:** These are not yet available inside of non-page Astro components. Instead, do all of your data loading inside of your pages, and then pass them to your components as props.
|
||||
|
||||
## Using `fetch()` outside of Astro Components
|
||||
|
||||
If you want to use `fetch()` in a non-astro component, use the [`node-fetch`](https://github.com/node-fetch/node-fetch) library:
|
||||
|
||||
```tsx
|
||||
// Movies.tsx
|
||||
import fetch from 'node-fetch';
|
||||
import type { FunctionalComponent } from 'preact';
|
||||
import { h } from 'preact';
|
||||
|
||||
const data = fetch('https://example.com/movies.json').then((response) =>
|
||||
response.json()
|
||||
);
|
||||
|
||||
// Components that are build-time rendered also log to the CLI.
|
||||
// If you loaded this component with a directive, it would log to the browser console.
|
||||
console.log(data);
|
||||
|
||||
const Movies: FunctionalComponent = () => {
|
||||
// Output the result to the page
|
||||
return <div>{JSON.stringify(data)}</div>;
|
||||
};
|
||||
|
||||
export default Movies;
|
||||
```
|
||||
|
||||
If you load a component using `node-fetch` [interactively](/core-concepts/component-hydration), with `client:load`, `client:visible`, etc., you'll need to either not use `node-fetch` or switch to an [isomorphic](https://en.wikipedia.org/wiki/Isomorphic_JavaScript) library that will run both at build time and on the client, as the [`node-fetch` README.md](https://github.com/node-fetch/node-fetch#motivation) recommends:
|
||||
|
||||
> Instead of implementing XMLHttpRequest in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native http to fetch API directly? Hence, node-fetch, minimal code for a window.fetch compatible API on Node.js runtime.
|
||||
>
|
||||
> See Jason Miller's [isomorphic-unfetch](https://www.npmjs.com/package/isomorphic-unfetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports node-fetch for server-side, whatwg-fetch for client-side).
|
||||
|
||||
> Quoted from https://github.com/node-fetch/node-fetch#motivation
|
335
docs/src/pages/group-10/guides/deploy.md
Normal file
335
docs/src/pages/group-10/guides/deploy.md
Normal file
|
@ -0,0 +1,335 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Deploy a Website
|
||||
---
|
||||
|
||||
The following guides are based on some shared assumptions:
|
||||
|
||||
- You are using the default build output location (`dist/`). This location [can be changed using the `dist` configuration option](/reference/configuration-reference).
|
||||
- You are using npm. You can use equivalent commands to run the scripts if you are using Yarn or other package managers.
|
||||
- Astro is installed as a local dev dependency in your project, and you have set up the following npm scripts:
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"start": "astro dev",
|
||||
"build": "astro build"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Building The App
|
||||
|
||||
You may run `npm run build` command to build the app.
|
||||
|
||||
```bash
|
||||
$ npm run build
|
||||
```
|
||||
|
||||
By default, the build output will be placed at `dist/`. You may deploy this `dist/` folder to any of your preferred platforms.
|
||||
|
||||
## GitHub Pages
|
||||
|
||||
1. Set the correct `buildOptions.site` in `astro.config.mjs`.
|
||||
1. Inside your project, create `deploy.sh` with the following content (uncommenting the appropriate lines), and run it to deploy:
|
||||
|
||||
```bash{13,20,23}
|
||||
#!/usr/bin/env sh
|
||||
|
||||
# abort on errors
|
||||
set -e
|
||||
|
||||
# build
|
||||
npm run build
|
||||
|
||||
# navigate into the build output directory
|
||||
cd dist
|
||||
|
||||
# add .nojekyll to bypass GitHub Page's default behavior
|
||||
touch .nojekyll
|
||||
|
||||
# if you are deploying to a custom domain
|
||||
# echo 'www.example.com' > CNAME
|
||||
|
||||
git init
|
||||
git add -A
|
||||
git commit -m 'deploy'
|
||||
|
||||
# if you are deploying to https://<USERNAME>.github.io
|
||||
# git push -f git@github.com:<USERNAME>/<USERNAME>.github.io.git main
|
||||
|
||||
# if you are deploying to https://<USERNAME>.github.io/<REPO>
|
||||
# git push -f git@github.com:<USERNAME>/<REPO>.git main:gh-pages
|
||||
|
||||
cd -
|
||||
```
|
||||
|
||||
> You can also run the above script in your CI setup to enable automatic deployment on each push.
|
||||
|
||||
### 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).
|
||||
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.
|
||||
5. In the astro project repo (not \<YOUR USERNAME\>.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 \<YOUR USERNAME\>.github.io for you.
|
||||
|
||||
```yaml
|
||||
# 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!
|
||||
env:
|
||||
githubEmail: <YOUR GITHUB EMAIL ADDRESS>
|
||||
deployToRepo: <NAME OF REPO TO DEPLOY TO (E.G. <YOUR USERNAME>.github.io)>
|
||||
|
||||
name: Github Pages Astro CI
|
||||
|
||||
on:
|
||||
# Triggers the workflow on push and pull request events but only for the main branch
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
# Allows you to run this workflow manually from the Actions tab.
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
|
||||
- uses: actions/checkout@v2
|
||||
|
||||
# Install dependencies with npm
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
# Build the project and add .nojekyll file to supress default behaviour
|
||||
- name: Build
|
||||
run: |
|
||||
npm run build
|
||||
touch ./dist/.nojekyll
|
||||
|
||||
# Push to your pages repo
|
||||
- name: Push to pages repo
|
||||
uses: cpina/github-action-push-to-another-repository@main
|
||||
env:
|
||||
API_TOKEN_GITHUB: ${{ secrets.API_TOKEN_GITHUB }}
|
||||
with:
|
||||
source-directory: 'dist'
|
||||
destination-github-username: ${{ github.actor }}
|
||||
destination-repository-name: ${{ env.deployToRepo }}
|
||||
user-email: ${{ env.githubEmail }}
|
||||
commit-message: Deploy ORIGIN_COMMIT
|
||||
target-branch: gh-pages
|
||||
```
|
||||
|
||||
### Travis CI
|
||||
|
||||
1. Set the correct `buildOptions.site` in `astro.config.mjs`.
|
||||
2. Create a file named `.travis.yml` in the root of your project.
|
||||
3. Run `npm install` locally and commit the generated lockfile (`package-lock.json`).
|
||||
4. Use the GitHub Pages deploy provider template, and follow the [Travis CI documentation](https://docs.travis-ci.com/user/deployment/pages/).
|
||||
|
||||
```yaml
|
||||
language: node_js
|
||||
node_js:
|
||||
- lts/*
|
||||
install:
|
||||
- npm ci
|
||||
script:
|
||||
- npm run build
|
||||
deploy:
|
||||
provider: pages
|
||||
skip_cleanup: true
|
||||
local_dir: dist
|
||||
# A token generated on GitHub allowing Travis to push code on you repository.
|
||||
# Set in the Travis settings page of your repository, as a secure variable.
|
||||
github_token: $GITHUB_TOKEN
|
||||
keep_history: true
|
||||
on:
|
||||
branch: master
|
||||
```
|
||||
|
||||
## GitLab Pages
|
||||
|
||||
1. Set the correct `buildOptions.site` in `astro.config.mjs`.
|
||||
2. Set `build.outDir` in `astro.config.mjs` to `public`.
|
||||
3. Create a file called `.gitlab-ci.yml` in the root of your project with the content below. This will build and deploy your site whenever you make changes to your content:
|
||||
|
||||
```yaml
|
||||
image: node:10.22.0
|
||||
pages:
|
||||
cache:
|
||||
paths:
|
||||
- node_modules/
|
||||
script:
|
||||
- npm install
|
||||
- npm run build
|
||||
artifacts:
|
||||
paths:
|
||||
- public
|
||||
only:
|
||||
- master
|
||||
```
|
||||
|
||||
## Netlify
|
||||
|
||||
In your codebase, make sure you have a `.nvmrc` file with `v14.15.1` in it.
|
||||
|
||||
You can configure your deploy in two ways, via the Netlify website or with the `netlify.toml` file.
|
||||
|
||||
With the `netlify.toml` file, add it at the top level of your project with the following settings:
|
||||
|
||||
```toml
|
||||
[build]
|
||||
command = "npm run build"
|
||||
publish = "dist"
|
||||
```
|
||||
|
||||
Then, set up a new project on [Netlify](https://netlify.com) from your chosen Git provider.
|
||||
|
||||
If you don't want to use the `netlify.toml`, when you go to [Netlify](https://netlify.com) and set up a new project from Git, input the following settings:
|
||||
|
||||
- **Build Command:** `astro build` or `npm run build`
|
||||
- **Publish directory:** `dist`
|
||||
|
||||
Then hit the deploy button.
|
||||
|
||||
## Google Firebase
|
||||
|
||||
1. Make sure you have [firebase-tools](https://www.npmjs.com/package/firebase-tools) installed.
|
||||
|
||||
2. Create `firebase.json` and `.firebaserc` at the root of your project with the following content:
|
||||
|
||||
`firebase.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"hosting": {
|
||||
"public": "dist",
|
||||
"ignore": []
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`.firebaserc`:
|
||||
|
||||
```js
|
||||
{
|
||||
"projects": {
|
||||
"default": "<YOUR_FIREBASE_ID>"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
3. After running `npm run build`, deploy using the command `firebase deploy`.
|
||||
|
||||
## Surge
|
||||
|
||||
1. First install [surge](https://www.npmjs.com/package/surge), if you haven't already.
|
||||
|
||||
2. Run `npm run build`.
|
||||
|
||||
3. Deploy to surge by typing `surge dist`.
|
||||
|
||||
You can also deploy to a [custom domain](http://surge.sh/help/adding-a-custom-domain) by adding `surge dist yourdomain.com`.
|
||||
|
||||
## Heroku
|
||||
|
||||
1. Install [Heroku CLI](https://devcenter.heroku.com/articles/heroku-cli).
|
||||
|
||||
2. Create a Heroku account by [signing up](https://signup.heroku.com).
|
||||
|
||||
3. Run `heroku login` and fill in your Heroku credentials:
|
||||
|
||||
```bash
|
||||
$ heroku login
|
||||
```
|
||||
|
||||
4. Create a file called `static.json` in the root of your project with the below content:
|
||||
|
||||
`static.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"root": "./dist"
|
||||
}
|
||||
```
|
||||
|
||||
This is the configuration of your site; read more at [heroku-buildpack-static](https://github.com/heroku/heroku-buildpack-static).
|
||||
|
||||
5. Set up your Heroku git remote:
|
||||
|
||||
```bash
|
||||
# version change
|
||||
$ git init
|
||||
$ git add .
|
||||
$ git commit -m "My site ready for deployment."
|
||||
|
||||
# creates a new app with a specified name
|
||||
$ heroku apps:create example
|
||||
|
||||
# set buildpack for static sites
|
||||
$ heroku buildpacks:set https://github.com/heroku/heroku-buildpack-static.git
|
||||
```
|
||||
|
||||
6. Deploy your site:
|
||||
|
||||
```bash
|
||||
# publish site
|
||||
$ git push heroku master
|
||||
|
||||
# opens a browser to view the Dashboard version of Heroku CI
|
||||
$ heroku open
|
||||
```
|
||||
|
||||
## Vercel
|
||||
|
||||
To deploy your Astro project with a [Vercel for Git](https://vercel.com/docs/git), make sure it has been pushed to a Git repository.
|
||||
|
||||
Go to https://vercel.com/import/git and import the project into Vercel using your Git of choice (GitHub, GitLab or BitBucket). Follow the wizard to select the project root with the project's `package.json` and override the build step using `npm run build` and the output dir to be `./dist`
|
||||
|
||||
After your project has been imported, all subsequent pushes to branches will generate Preview Deployments, and all changes made to the Production Branch (commonly "main") will result in a Production Deployment.
|
||||
|
||||
Once deployed, you will get a URL to see your app live, such as the following: https://astro.vercel.app
|
||||
|
||||
## Azure Static Web Apps
|
||||
|
||||
You can deploy your Astro project with Microsoft Azure [Static Web Apps](https://aka.ms/staticwebapps) service. You need:
|
||||
|
||||
- An Azure account and a subscription key. You can create a [free Azure account here](https://azure.microsoft.com/free).
|
||||
- Your app code pushed to [GitHub](https://github.com).
|
||||
- The [SWA Extension](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-azurestaticwebapps) in [Visual Studio Code](https://code.visualstudio.com).
|
||||
|
||||
Install the extension in VS Code and navigate to your app root. Open the Static Web Apps extension, sign in to Azure, and click the '+' sign to create a new Static Web App. You will be prompted to designate which subscription key to use.
|
||||
|
||||
Follow the wizard started by the extension to give your app a name, choose a framework preset, and designate the app root (usually `/`) and built file location `/dist`. The wizard will run and will create a GitHub action in your repo in a `.github` folder.
|
||||
|
||||
The action will work to deploy your app (watch its progress in your repo's Actions tab) and, when successfully completed, you can view your app in the address provided in the extension's progress window by clicking the 'Browse Website' button that appears when the GitHub action has run.
|
||||
|
||||
## Cloudflare Pages
|
||||
|
||||
You can deploy your Astro project on [Cloudflare Pages](https://pages.cloudflare.com). You need:
|
||||
|
||||
- A Cloudflare account. If you don’t already have one, you can create a free Cloudflare account during the process.
|
||||
- Your app code pushed to a [GitHub](https://github.com) repository.
|
||||
|
||||
Then, set up a new project on Cloudflare Pages.
|
||||
|
||||
Use the following build settings:
|
||||
|
||||
- **Framework preset**: `None` (As of this writing, Astro is not listed.)
|
||||
- **Build command:** `astro build` or `npm run build`
|
||||
- **Build output directory:** `dist`
|
||||
- **Environment variables (advanced)**: Add an environment variable with the **Variable name** of `NODE_VERSION` and a **Value** of a [Node version that’s compatible with Astro](https://docs.astro.build/installation#prerequisites), since the Cloudflare Pages default version probably won’t work.
|
||||
|
||||
Then click the **Save and Deploy** button.
|
||||
|
||||
## Credits
|
||||
|
||||
This guide was originally based off [Vite](https://vitejs.dev/)’s well-documented static deploy guide.
|
139
docs/src/pages/group-10/guides/imports.md
Normal file
139
docs/src/pages/group-10/guides/imports.md
Normal file
|
@ -0,0 +1,139 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Supported Imports
|
||||
---
|
||||
|
||||
Astro uses Snowpack as its internal build system. Snowpack provides Astro with built-in support for the following file types, with no configuration required:
|
||||
|
||||
- JavaScript (`.js`, `.mjs`)
|
||||
- TypeScript (`.ts`, `.tsx`)
|
||||
- JSON (`.json`)
|
||||
- JSX (`.jsx`, `.tsx`)
|
||||
- CSS (`.css`)
|
||||
- CSS Modules (`.module.css`)
|
||||
- Images & Assets (`.svg`, `.jpg`, `.png`, etc.)
|
||||
- Astro Components (`.astro`)
|
||||
- Markdown (`.md`)
|
||||
- WASM (`.wasm`)
|
||||
|
||||
Any files in your `public/` directory are copied into the final build, untouched by Snowpack or Astro. The following applies to files in your `src/` directory, which Astro is ultimately responsible for.
|
||||
|
||||
## JavaScript & ESM
|
||||
|
||||
Astro was designed for JavaScript's native ES Module (ESM) syntax. ESM lets you define explicit imports & exports that browsers and build tools can better understand and optimize for. If you're familiar with the `import` and `export` keywords in JavaScript, then you already know ESM!
|
||||
|
||||
```js
|
||||
// ESM Example - src/user.js
|
||||
export function getUser() {
|
||||
/* ... */
|
||||
}
|
||||
|
||||
// src/index.js
|
||||
import { getUser } from './user.js';
|
||||
```
|
||||
|
||||
All browsers now support ESM, so Astro is able to ship this code directly to the browser during development.
|
||||
|
||||
## TypeScript
|
||||
|
||||
Astro includes built-in support to build TypeScript files (`*.ts`) to JavaScript. Astro components also support TypeScript in the frontmatter script section.
|
||||
|
||||
Note that this built-in support is build only. By default, Astro does not type-check your TypeScript code.
|
||||
|
||||
<!-- To integrate type checking into your development/build workflow, add the [@snowpack/plugin-typescript](https://www.npmjs.com/package/@snowpack/plugin-typescript) plugin. -->
|
||||
|
||||
## JSX
|
||||
|
||||
Astro includes built-in support to build JSX files (`*.jsx` & `*.tsx`) to JavaScript.
|
||||
|
||||
If you are using Preact, Astro will detect your Preact import and switch to use the Preact-style JSX `h()` function. This is all done automatically for you.
|
||||
|
||||
**Note: Astro does not support JSX in `.js`/`.ts` files.**
|
||||
|
||||
## JSON
|
||||
|
||||
```js
|
||||
// Load the JSON object via the default export
|
||||
import json from './data.json';
|
||||
```
|
||||
|
||||
Astro supports importing JSON files directly into your application. Imported files return the full JSON object in the default import.
|
||||
|
||||
## CSS
|
||||
|
||||
```js
|
||||
// Load and inject 'style.css' onto the page
|
||||
import './style.css';
|
||||
```
|
||||
|
||||
Astro supports importing CSS files directly into your application. Imported styles expose no exports, but importing one will automatically add those styles to the page. This works for all CSS files by default, and can support compile-to-CSS languages like Sass & Less via plugins.
|
||||
|
||||
If you prefer not to write CSS, Astro also supports all popular CSS-in-JS libraries (ex: styled-components) for styling.
|
||||
|
||||
## CSS Modules
|
||||
|
||||
```js
|
||||
// 1. Converts './style.module.css' classnames to unique, scoped values.
|
||||
// 2. Returns an object mapping the original classnames to their final, scoped value.
|
||||
import styles from './style.module.css';
|
||||
|
||||
// This example uses JSX, but you can use CSS Modules with any framework.
|
||||
return <div className={styles.error}>Your Error Message</div>;
|
||||
```
|
||||
|
||||
Astro supports CSS Modules using the `[name].module.css` naming convention. Like any CSS file, importing one will automatically apply that CSS to the page. However, CSS Modules export a special default `styles` object that maps your original classnames to unique identifiers.
|
||||
|
||||
CSS Modules help you enforce component scoping & isolation on the frontend with unique-generated class names for your stylesheets.
|
||||
|
||||
## Other Assets
|
||||
|
||||
```jsx
|
||||
import imgReference from './image.png'; // img === '/src/image.png'
|
||||
import svgReference from './image.svg'; // svg === '/src/image.svg'
|
||||
import txtReference from './words.txt'; // txt === '/src/words.txt'
|
||||
|
||||
// This example uses JSX, but you can use import references with any framework.
|
||||
<img src={imgReference} />;
|
||||
```
|
||||
|
||||
All other assets not explicitly mentioned above can be imported via ESM `import` and will return a URL reference to the final built asset. This can be useful for referencing non-JS assets by URL, like creating an image element with a `src` attribute pointing to that image.
|
||||
|
||||
## WASM
|
||||
|
||||
```js
|
||||
// Loads and intializes the requested WASM file
|
||||
const wasm = await WebAssembly.instantiateStreaming(fetch('/example.wasm'));
|
||||
```
|
||||
|
||||
Astro supports loading WASM files directly into your application using the browser's [`WebAssembly`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly) API. Read our [WASM guide](/guides/wasm) to learn more.
|
||||
|
||||
## NPM Packages
|
||||
|
||||
```js
|
||||
// Returns the React & React-DOM npm packages
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
```
|
||||
|
||||
Astro lets you import npm packages directly in the browser. Even if a package was published using a legacy format, Astro will up-convert the package to ESM before serving it to the browser.
|
||||
|
||||
When you start up your dev server or run a new build, you may see a message that Snowpack is "installing dependencies". This means that Snowpack is converting your dependencies to run in the browser. This needs to run only once, or until you next change your dependency tree by adding or removing dependencies.
|
||||
|
||||
## Node Builtins
|
||||
|
||||
We encourage Astro users to avoid Node.js builtins (`fs`, `path`, etc) whenever possible. Astro aims to be compatible with multiple JavaScript runtimes in the future. This includes [Deno](https://deno.land/) and [Cloudflare Workers](https://workers.cloudflare.com/) which do not support Node builtin modules such as `fs`.
|
||||
|
||||
Our aim is to provide Astro alternatives to common Node.js builtins. However, no such alternatives exist today. So, if you _really_ need to use these builtin modules we don't want to stop you. Astro supports Node.js builtins using Node's newer `node:` prefix. If you want to read a file, for example, you can do so like this:
|
||||
|
||||
```jsx
|
||||
---
|
||||
// Example: import the "fs/promises" builtin from Node.js
|
||||
import fs from 'node:fs/promises';
|
||||
|
||||
const url = new URL('../../package.json', import.meta.url);
|
||||
const json = await fs.readFile(url, 'utf-8');
|
||||
const data = JSON.parse(json);
|
||||
---
|
||||
|
||||
<span>Version: {data.version}</span>
|
||||
```
|
223
docs/src/pages/group-10/guides/markdown-content.md
Normal file
223
docs/src/pages/group-10/guides/markdown-content.md
Normal file
|
@ -0,0 +1,223 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Markdown
|
||||
---
|
||||
|
||||
Astro comes with out-of-the-box Markdown support powered by the expansive [remark](https://remark.js.org/) ecosystem.
|
||||
|
||||
## Remark and Rehype Plugins
|
||||
|
||||
In addition to custom components inside the [`<Markdown>` component](/guides/markdown-content#astros-markdown-component), Astro comes with [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) and syntax highlighting via [Prism](https://prismjs.com/) pre-enabled.
|
||||
|
||||
Also, Astro supports third-party plugins for Markdown. You can provide your plugins in `astro.config.mjs`.
|
||||
|
||||
> **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
|
||||
|
||||
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:
|
||||
|
||||
```js
|
||||
// astro.config.mjs
|
||||
export default {
|
||||
markdownOptions: {
|
||||
remarkPlugins: [
|
||||
// Add a Remark plugin that you want to enable for your project.
|
||||
// If you need to provide options for the plugin, you can use an array and put the options as the second item.
|
||||
// ['remark-autolink-headings', { behavior: 'prepend'}],
|
||||
],
|
||||
rehypePlugins: [
|
||||
// Add a Rehype plugin that you want to enable for your project.
|
||||
// If you need to provide options for the plugin, you can use an array and put the options as the second item.
|
||||
// 'rehype-slug',
|
||||
// ['rehype-autolink-headings', { behavior: 'prepend'}],
|
||||
],
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
You can provide names of the plugins as well as import them:
|
||||
|
||||
```js
|
||||
// astro.config.mjs
|
||||
export default {
|
||||
markdownOptions: {
|
||||
remarkPlugins: [
|
||||
[import('remark-autolink-headings'), { behavior: 'prepend' }],
|
||||
],
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
### Markdown Pages
|
||||
|
||||
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.
|
||||
|
||||
`layout`
|
||||
|
||||
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
|
||||
---
|
||||
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 `<slot />` element.
|
||||
|
||||
`src/layouts/main.astro`
|
||||
|
||||
```jsx
|
||||
---
|
||||
const { content } = Astro.props;
|
||||
---
|
||||
|
||||
<html>
|
||||
<head>
|
||||
<title>{content.title}</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<slot/>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
### 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 `<Markdown>` component, within your frontmatter block use the following import statement:
|
||||
|
||||
```jsx
|
||||
---
|
||||
import { Markdown } from 'astro/components';
|
||||
---
|
||||
```
|
||||
|
||||
You can utilize this within your `.astro` file by doing the following:
|
||||
|
||||
```jsx
|
||||
---
|
||||
import { Markdown } from 'astro/components';
|
||||
---
|
||||
|
||||
<Layout>
|
||||
<Markdown>
|
||||
# Hello world!
|
||||
|
||||
The contents inside here is all in markdown.
|
||||
</Markdown>
|
||||
</Layout>
|
||||
```
|
||||
|
||||
`<Markdown>` components provide more flexibility and allow you to use plain HTML or custom components. For example:
|
||||
|
||||
````jsx
|
||||
---
|
||||
// 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 MyFancyCodePreview from '../components/MyFancyCodePreview.tsx';
|
||||
|
||||
const expressions = 'Lorem ipsum';
|
||||
---
|
||||
|
||||
<Layout>
|
||||
<Markdown>
|
||||
# Hello world!
|
||||
|
||||
**Everything** supported in a `.md` file is also supported here!
|
||||
|
||||
There is _zero_ runtime overhead.
|
||||
|
||||
In addition, Astro supports:
|
||||
- Astro {expressions}
|
||||
- Automatic indentation normalization
|
||||
- Automatic escaping of expressions inside code blocks
|
||||
|
||||
```jsx
|
||||
// This content is not transformed!
|
||||
const object = { someOtherValue };
|
||||
```
|
||||
|
||||
- Rich component support like any `.astro` file!
|
||||
- Recursive Markdown support (Component children are also processed as Markdown)
|
||||
|
||||
<MyFancyCodePreview client:visible>
|
||||
```jsx
|
||||
const object = { someOtherValue };
|
||||
```
|
||||
</MyFancyCodePreview client:visible>
|
||||
</Markdown>
|
||||
</Layout>
|
||||
````
|
||||
|
||||
### 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.
|
||||
|
||||
```jsx
|
||||
---
|
||||
import { Markdown } from 'astro/components';
|
||||
|
||||
const content = await fetch('https://raw.githubusercontent.com/snowpackjs/snowpack/main/README.md').then(res => res.text());
|
||||
---
|
||||
|
||||
<Layout>
|
||||
<Markdown content={content} />
|
||||
</Layout>
|
||||
```
|
||||
|
||||
There might be times when you want to combine both dynamic, and static markdown. If that is the case, you can nest `<Markdown>` components with each other to get the best of both worlds.
|
||||
|
||||
```jsx
|
||||
---
|
||||
import { Markdown } from 'astro/components';
|
||||
|
||||
const content = await fetch('https://raw.githubusercontent.com/snowpackjs/snowpack/main/README.md').then(res => res.text());
|
||||
---
|
||||
|
||||
<Layout>
|
||||
<Markdown>
|
||||
## Markdown example
|
||||
|
||||
Here we have some __Markdown__ code. We can also dynamically render content from remote places.
|
||||
|
||||
<Markdown content={content} />
|
||||
</Mardown>
|
||||
</Layout>
|
||||
```
|
||||
|
||||
### Security FAQs
|
||||
|
||||
**Aren't there security concerns to rendering remote markdown directly to HTML?**
|
||||
|
||||
Yes! Just like with regular HTML, improper use of the `Markdown` component can open you up to a [cross-site scripting (XSS)](https://en.wikipedia.org/wiki/Cross-site_scripting) attack. If you are rendering untrusted content, be sure to _sanitize your content **before** rendering it_.
|
||||
|
||||
**Why not use a prop like React's `dangerouslySetInnerHTML={{ __html: content }}`?**
|
||||
|
||||
Rendering a string of HTML (or Markdown) is an extremely common use case when rendering a static site and you probably don't need the extra hoops to jump through. Rendering untrusted content is always dangerous! Be sure to _sanitize your content **before** rendering it_.
|
100
docs/src/pages/group-10/guides/publish-to-npm.md
Normal file
100
docs/src/pages/group-10/guides/publish-to-npm.md
Normal file
|
@ -0,0 +1,100 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Publish a Component to NPM
|
||||
---
|
||||
|
||||
Built a great Astro component? **Publish it to [npm!](https://npmjs.com/)**
|
||||
|
||||
Once published to npm, Astro components can be installed and used in your project like any other npm package. npm is a great way to share Astro components across projects within your team, your company, or the entire world.
|
||||
|
||||
## Basic NPM Package Setup
|
||||
|
||||
Here's an example package that we'd like to publish to npm. It includes two Astro components and a few other files.
|
||||
|
||||
```
|
||||
/my-components-package/
|
||||
├── package.json
|
||||
├── index.js
|
||||
├── Capitalize.astro
|
||||
└── Bold.astro
|
||||
```
|
||||
|
||||
### `package.json`
|
||||
|
||||
Your package manifest. This includes information about your package such as name, description, any dependencies, and other important metadata. If you don't know what the `package.json` file is, we highly recommend you to have a quick read on [the npm documentation](https://docs.npmjs.com/creating-a-package-json-file).
|
||||
|
||||
When making a astro component use the `astro-component` keyword, this makes it easier for people to find your component.
|
||||
|
||||
We recommend that you define an [exports entry](https://nodejs.org/api/packages.html) for your `index.js` package entrypoint like so:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "@example/my-components",
|
||||
"version": "0.0.1",
|
||||
"exports": "./index.js",
|
||||
"keywords": ["astro-component"]
|
||||
}
|
||||
```
|
||||
|
||||
### `index.js`
|
||||
|
||||
`index.js` is your package entrypoint, which is the file that gets loaded when someone imports your package by name. Having a JavaScript file as your package entrypoint will let you export multiple components and have better control over their exported component names.
|
||||
|
||||
```js
|
||||
export { default as Capitalize } from './Capitalize.astro';
|
||||
export { default as Bold } from './Bold.astro';
|
||||
```
|
||||
|
||||
### Publishing
|
||||
|
||||
Once you have your package ready, you can publish it to npm by running the command `npm publish`. If that fails, make sure that you've logged in via `npm login` and that your package.json is correct.
|
||||
|
||||
Once published, anyone will be able to install your components and then import them like so:
|
||||
|
||||
```astro
|
||||
---
|
||||
import { Bold, Capitalize } from '@example/my-components';
|
||||
---
|
||||
<Capitalize phrase={`Hello world`} />
|
||||
```
|
||||
|
||||
## Advanced
|
||||
|
||||
We recommend a single `index.js` package entrypoint because this is what most users are familiar with. However, in some rare scenarios you may want to have your users import each `.astro` component directly, in the same manner that you import `.astro` files in your own project.
|
||||
|
||||
```astro
|
||||
---
|
||||
import Capitalize from '@example/my-components/Capitalize.astro';
|
||||
---
|
||||
<Capitalize phrase={`Hello world`} />
|
||||
```
|
||||
|
||||
This is a less common scenario, and we only recommend it if you have good reason. Because Astro is completely rendered at build-time, there are no client-side performance concerns to our default recommendation to export your components from a single `index.js` file.
|
||||
|
||||
To support importing by file within your package, add each file to your **package.json** `exports` map:
|
||||
|
||||
```diff
|
||||
{
|
||||
"name": "@example/my-components",
|
||||
"version": "1.0.0",
|
||||
"exports": {
|
||||
- ".": "./index.js",
|
||||
+ "./Bold.astro": "./Bold.astro",
|
||||
+ "./Capitalize.astro": "./Capitalize.astro"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Community components
|
||||
|
||||
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.
|
||||
|
||||
You can also [search npm for astro components.](https://www.npmjs.com/search?q=keywords%3Aastro-component)
|
||||
|
||||
Did you make a component?
|
||||
|
||||
[Create a PR to submit your component in these docs](https://github.com/snowpackjs/astro/issues/new/choose)
|
566
docs/src/pages/group-10/guides/styling.md
Normal file
566
docs/src/pages/group-10/guides/styling.md
Normal file
|
@ -0,0 +1,566 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Styling & CSS
|
||||
---
|
||||
|
||||
Astro includes special handling to make writing CSS as easy as possible. Styling inside of Astro components is done by adding a `<style>` tag anywhere.
|
||||
|
||||
By default, all Astro component styles are **scoped**, meaning they only apply to the current component. These styles are automatically extracted and optimized for you in the final build, so that you don't need to worry about style loading.
|
||||
|
||||
To create global styles, add a `:global()` wrapper around a selector (the same as if you were using [CSS Modules][css-modules]).
|
||||
|
||||
```html
|
||||
<!-- src/components/MyComponent.astro -->
|
||||
<style>
|
||||
/* Scoped class selector within the component */
|
||||
.scoped {
|
||||
font-weight: bold;
|
||||
}
|
||||
/* Scoped element selector within the component */
|
||||
h1 {
|
||||
color: red;
|
||||
}
|
||||
/* Global style */
|
||||
:global(h1) {
|
||||
font-size: 32px;
|
||||
}
|
||||
</style>
|
||||
|
||||
<div class="scoped">I'm a scoped style and only apply to this component</div>
|
||||
<h1>I have both scoped and global styles</h1>
|
||||
```
|
||||
|
||||
To include every selector in a `<style>` as global styles, use `<style global>`. It's best to avoid using this escape hatch if possible, but it can be useful if you find yourself repeating `:global()` multiple times in the same `<style>`.
|
||||
|
||||
```html
|
||||
<!-- src/components/MyComponent.astro -->
|
||||
<style>
|
||||
/* Scoped class selector within the component */
|
||||
.scoped {
|
||||
font-weight: bold;
|
||||
}
|
||||
/* Scoped element selector within the component */
|
||||
h1 {
|
||||
color: red;
|
||||
}
|
||||
</style>
|
||||
|
||||
<style global>
|
||||
/* Global style */
|
||||
h1 {
|
||||
font-size: 32px;
|
||||
}
|
||||
</style>
|
||||
|
||||
<div class="scoped">I'm a scoped style and only apply to this component</div>
|
||||
<h1>I have both scoped and global styles</h1>
|
||||
```
|
||||
|
||||
📚 Read our full guide on [Astro component syntax](/core-concepts/astro-components#css-styles) to learn more about using the `<style>` tag.
|
||||
|
||||
## Cross-Browser Compatibility
|
||||
|
||||
We also automatically add browser prefixes using [Autoprefixer][autoprefixer]. By default, Astro loads the [Browserslist defaults][browserslist-defaults], but you may also specify your own by placing a [Browserslist][browserslist] file in your project root.
|
||||
|
||||
---
|
||||
|
||||
## Supported Styling Options
|
||||
|
||||
Styling in Astro is meant to be as flexible as you'd like it to be! The following options are all supported:
|
||||
|
||||
| Framework | Global CSS | Scoped CSS | CSS Modules |
|
||||
| :--------------- | :--------: | :--------: | :---------: |
|
||||
| `.astro` | ✅ | ✅ | N/A¹ |
|
||||
| `.jsx` \| `.tsx` | ✅ | ❌ | ✅ |
|
||||
| `.vue` | ✅ | ✅ | ✅ |
|
||||
| `.svelte` | ✅ | ✅ | ❌ |
|
||||
|
||||
¹ _`.astro` files have no runtime, therefore Scoped CSS takes the place of CSS Modules (styles are still scoped to components, but don't need dynamic values)_
|
||||
|
||||
All styles in Astro are automatically [**autoprefixed**](#cross-browser-compatibility), minified and bundled, so you can just write CSS and we'll handle the rest ✨.
|
||||
|
||||
---
|
||||
|
||||
## Frameworks and Libraries
|
||||
|
||||
### 📘 React / Preact
|
||||
|
||||
`.jsx` files support both global CSS and CSS Modules. To enable the latter, use the `.module.css` extension (or `.module.scss`/`.module.sass` if using Sass).
|
||||
|
||||
```js
|
||||
import './global.css'; // include global CSS
|
||||
import Styles from './styles.module.css'; // Use CSS Modules (must end in `.module.css`, `.module.scss`, or `.module.sass`!)
|
||||
```
|
||||
|
||||
### 📗 Vue
|
||||
|
||||
Vue in Astro supports the same methods as `vue-loader` does:
|
||||
|
||||
- [vue-loader - Scoped CSS][vue-scoped]
|
||||
- [vue-loader - CSS Modules][vue-css-modules]
|
||||
|
||||
### 📕 Svelte
|
||||
|
||||
Svelte in Astro also works exactly as expected: [Svelte Styling Docs][svelte-style].
|
||||
|
||||
### 👓 Sass
|
||||
|
||||
Astro also supports [Sass][sass] out-of-the-box. To enable for each framework:
|
||||
|
||||
- **Astro**: `<style lang="scss">` or `<style lang="sass">`
|
||||
- **React** / **Preact**: `import Styles from './styles.module.scss'`;
|
||||
- **Vue**: `<style lang="scss">` or `<style lang="sass">`
|
||||
- **Svelte**: `<style lang="scss">` or `<style lang="sass">`
|
||||
|
||||
💁 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 `./public/style/global.scss`, use this link: `<link rel="stylesheet" href="/style/global.css">` — **not** `<link rel="stylesheet" href="/style/global.scss">`.
|
||||
|
||||
### 🍃 Tailwind
|
||||
|
||||
Astro can be configured to use [Tailwind][tailwind] easily! Install the dependencies:
|
||||
|
||||
```
|
||||
npm install --save-dev tailwindcss
|
||||
```
|
||||
|
||||
And also create a `tailwind.config.js` in your project root:
|
||||
|
||||
```js
|
||||
// tailwind.config.js
|
||||
module.exports = {
|
||||
mode: 'jit',
|
||||
purge: ['./public/**/*.html', './src/**/*.{astro,js,jsx,svelte,ts,tsx,vue}'],
|
||||
// more options here
|
||||
};
|
||||
```
|
||||
|
||||
Be sure to add the config path to `astro.config.mjs`, so that Astro enables JIT support in the dev server.
|
||||
|
||||
```diff
|
||||
// astro.config.mjs
|
||||
export default {
|
||||
+ devOptions: {
|
||||
+ tailwindConfig: './tailwind.config.js',
|
||||
+ },
|
||||
};
|
||||
```
|
||||
|
||||
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
|
||||
/* public/global.css */
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
```
|
||||
|
||||
As an alternative to `public/global.css`, You may also add Tailwind utilities to individual `pages/*.astro` components in `<style>` tags, but be mindful of duplication! If you end up creating multiple Tailwind-managed stylesheets for your site, make sure you're not sending the same CSS to users over and over again in separate CSS files.
|
||||
|
||||
### Importing from npm
|
||||
|
||||
If you want to import third-party libraries into an Astro component, you can use a `<style lang="scss">` tag to enable [Sass][sass] and use the [@use][sass-use] rule.
|
||||
|
||||
```html
|
||||
<!-- Loads Boostrap -->
|
||||
<style lang="scss">
|
||||
@use "bootstrap/scss/bootstrap";
|
||||
</style>
|
||||
```
|
||||
|
||||
### 🎭 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 -->
|
||||
---
|
||||
<style lang="scss">
|
||||
/* ✅ Locally scoped! */
|
||||
.btn {
|
||||
padding: 0.5em 1em;
|
||||
border-radius: 3px;
|
||||
font-weight: 700;
|
||||
}
|
||||
</style>
|
||||
<button type="button" class="btn">
|
||||
<slot></slot>
|
||||
</button>
|
||||
```
|
||||
|
||||
_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 `<style global>` escape hatches. However, this should be avoided if possible. To illustrate this: say you used your button in a `<Nav />` component, and you wanted to style it differently there. You might be tempted to have something like:
|
||||
|
||||
```jsx
|
||||
---
|
||||
// src/components/Nav.astro
|
||||
import Button from './Button.astro';
|
||||
---
|
||||
|
||||
<style lang="scss">
|
||||
.nav :global(.btn) {
|
||||
/* ❌ This will fight with <Button>'s styles */
|
||||
}
|
||||
</style>
|
||||
|
||||
<nav class="nav">
|
||||
<Button>Menu</Button>
|
||||
</nav>
|
||||
```
|
||||
|
||||
This is undesirable because now `<Nav>` and `<Button>` fight over what the final button looks like. Now, whenever you edit one, you'll always have to edit the other, and they are no longer truly isolated as they once were (now coupled by a bidirectional styling dependency). It's easy to see how this pattern only has to repeated a couple times before being afraid that touching any styles _anywhere_ may break styling in a completely different part of the app (queue `peter-griffin-css-blinds.gif`).
|
||||
|
||||
Instead, let `<Button>` control its own styles, and try a prop:
|
||||
|
||||
```jsx
|
||||
---
|
||||
// src/components/Button.astro
|
||||
const { theme } = Astro.props;
|
||||
---
|
||||
<style lang="scss">
|
||||
.btn {
|
||||
/* ✅ <Button> is now back in control of its own styling again! */
|
||||
[data-theme='nav'] {
|
||||
// nav-friendly styles here…
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<button type="button" data-theme={theme}>
|
||||
<slot></slot>
|
||||
</button>
|
||||
```
|
||||
|
||||
Elsewhere, you can use `<Button theme="nav">` to set the type of button it is. This preserves the contract of _Button is in charge of its styles, and Nav is in charge of its styles_, and now you can edit one without affecting the other. The worst case scenario of using global styles is that the component is broken and unusable (it's missing part of its core styles). But the worst case scenario of using props (e.g. typo) is that a component will only fall back to its default, but still usable, state.
|
||||
|
||||
💁 **Why this works well in Astro**: Astro is inspired most by JavaScript modules: you only need to know about what's in one file at a time, and you never have to worry about something in a remote file affecting how this code runs. But we're not alone in this; Vue and Svelte have both capitalized on and popularized the idea that styles and markup are natural fits in the same component file. [You can still have separation of concerns][peace-on-css] even with markup, styling, and logic contained in one file. In fact, that's what makes component design so powerful! So write CSS without fear that you picked a name that's used by some other component across your app.
|
||||
|
||||
#### Utility CSS
|
||||
|
||||
Recently there has been a debate of all-scoped component styles vs utility-only CSS. But we agree with people like Sarah Dayan who ask [why can't we have both][utility-css]? Truth is that while having scoped component styles are great, there are still hundreds of times when the website's coming together when two components just don't line up _quite_ right, and one needs a nudge. Or different text treatment is needed in one component instance.
|
||||
|
||||
While the thought of having perfect, pristine components is nice, it's unrealistic. No design system is absoutely perfect, and every design system has inconsistencies. And it's in reconciling these inconsistencies where components can become a mess without utility CSS. Utility CSS is great for adding minor tweaks necessary to get the website out the door. But they also are incomplete on their own—if you've ever tried to manage responsive styles or accessible focus states with utility CSS it can quickly become a mess! **Utility CSS works best in partnership with component (scoped) CSS**. And in order to be as easy as possible to use, Utility CSS should be global (arguably should be your only global CSS, besides maybe reset.css) so you don't have to deal with imports all willy-nilly.
|
||||
|
||||
Some great problems best handled with Utility CSS are:
|
||||
|
||||
- [margin](https://github.com/drwpow/sass-utils#-margin--padding)
|
||||
- [padding](https://github.com/drwpow/sass-utils#-margin--padding)
|
||||
- [text/background color](https://github.com/drwpow/sass-utils#-color)
|
||||
- [font size and family](https://github.com/drwpow/sass-utils#%F0%9F%85%B0%EF%B8%8F-font--text)
|
||||
- [default element styling](https://github.com/kognise/water.css)
|
||||
|
||||
In Astro, we recommend the following setup for this:
|
||||
|
||||
```html
|
||||
<head>
|
||||
<link rel="stylesheet" href="/styles/global.css" />
|
||||
</head>
|
||||
```
|
||||
|
||||
And in your local filesystem, you can even use Sass' [@use][sass-use] to combine files together effortlessly:
|
||||
|
||||
```
|
||||
├── public/
|
||||
│ └── styles/
|
||||
│ ├── _base.scss
|
||||
│ ├── _tokens.scss
|
||||
│ ├── _typography.scss
|
||||
│ ├── _utils.scss
|
||||
│ └── global.scss
|
||||
└── src/
|
||||
└── (pages)
|
||||
```
|
||||
|
||||
What's in each file is up to you to determine, but start small, add utilities as you need them, and you'll keep your CSS weight incredibly low. And utilities you wrote to meet your real needs will always be better than anything off the shelf.
|
||||
|
||||
So to recap, think of scoped styles as the backbone of your styles that get you 80% of the way there, and utility CSS filling in the remaining 20%. They both work well in tandem, with each compensating for the other's weakness.
|
||||
|
||||
💁 **Why this works well in Astro**: Astro was built around the idea of **Scoped CSS and Global Utility CSS living together in harmony** ♥️! Take full advantage of it.
|
||||
|
||||
### More suggestions
|
||||
|
||||
"But wait!" you may ask, having read the previous section. "That doesn't take care of [my usecase]!" If you‘re looking for more pointers on some common styling problems, you may be interested in the following suggestions. These all are cohesive, and fit with the **Hybrid Scoped + Utility** philosophy:
|
||||
|
||||
1. Split your app into Layout Components and Base Components
|
||||
1. Avoid Flexbox and Grid libraries (write your own!)
|
||||
1. Avoid `margin` on a component wrapper
|
||||
1. Avoid global media queries
|
||||
|
||||
#### Suggestion #1: Split your app into Layout Components and Base Components
|
||||
|
||||
While this guide will never be long enough to answer the question _"How should a page be laid out?"_ (that's a [design problem!][cassie-evans-css]) there is a more specific question hiding within that we _can_ answer: _"Given a layout, how should components/styles be organized?"_ The answer is **don't bake layout into components.** Have layout components that control layout, and base components (buttons, cards, etc.) that don't control layout. _What does that mean?_ Let's walk through an example so it's more clear. Pretend we have a page that looks like this (numbers for different components):
|
||||
|
||||
```
|
||||
|---------------|
|
||||
| 1 |
|
||||
|-------+-------|
|
||||
| 2 | 2 |
|
||||
|---+---|---+---|
|
||||
| 3 | 3 | 3 | 3 |
|
||||
|---+---+---+---|
|
||||
| 3 | 3 | 3 | 3 |
|
||||
|---+---+---+---|
|
||||
```
|
||||
|
||||
The layout consists of a big, giant, full-width post at top, followed by two half-width posts below it. And below that, we want a bunch of smaller posts to fill out the rest of the page. For simplicity, we'll just call these `<BigPost>` (1), `<MediumPost>` (2), and `<SmallPost>` (3). We add them to our page like so:
|
||||
|
||||
```jsx
|
||||
---
|
||||
// src/pages/index.astro
|
||||
|
||||
import Nav from '../components/Nav.astro';
|
||||
import BigPost from '../components/BigPost.astro';
|
||||
import Grid from '../components/Grid.astro';
|
||||
import MediumPosts from '../components/MediumPosts.astro';
|
||||
import SmallPosts from '../components/SmallPosts.astro';
|
||||
import Footer from '../components/Footer.astro';
|
||||
---
|
||||
<html>
|
||||
<body>
|
||||
<Nav />
|
||||
|
||||
<Grid>
|
||||
<BigPost />
|
||||
<MediumPosts />
|
||||
<SmallPosts />
|
||||
</Grid>
|
||||
|
||||
<Footer />
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
This _looks_ clean, but looks can be deceiving. At first glance, we may think that `<Grid>` is controlling the layout, but that's an illusion. We actually have `<BigPost>` handling its own width, `<MediumPosts>` loading 2 components and controlling its width, and `<SmallPosts>` loading 4+ components and controlling its width. In total, including `<Grid>`, that means **4 components** are all fighting over the same layout. Remove one post from `<MediumPosts>`, the layout breaks. Edit `<BigPost>`, the layout breaks. Edit `<Grid>`, the layout breaks. If you think about it, none of these components are truly reusable—they might as well just be one big file.
|
||||
|
||||
This is actually the **Global CSS Problem** in disguise—multiple components fight over how they all lay out together, without layout being one, central responsibility (kinda like global CSS)! Now that we identified the problem, one way to fix this is to hoist the entire layout to the top level, and load all components there, too:
|
||||
|
||||
```jsx
|
||||
---
|
||||
// src/pages/index.astro
|
||||
|
||||
import Nav from '../components/Nav.astro';
|
||||
import BigPost from '../components/BigPost.astro';
|
||||
import MediumPost from '../components/MediumPost.astro';
|
||||
import SmallPost from '../components/SmallPost.astro';
|
||||
import Footer from '../components/Footer.astro';
|
||||
---
|
||||
|
||||
<html>
|
||||
<head>
|
||||
<style lang="scss">
|
||||
.wrapper {
|
||||
max-width: 60rem;
|
||||
margin-right: auto;
|
||||
margin-left: auto;
|
||||
padding-right: 2rem;
|
||||
padding-left: 2rem;
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-gap: 1.5rem;
|
||||
grid-template columns: 1fr 1fr 1fr 1fr;
|
||||
}
|
||||
|
||||
.big-post {
|
||||
grid-column: span 4;
|
||||
}
|
||||
|
||||
.medium-post {
|
||||
grid-column: span 2;
|
||||
}
|
||||
|
||||
.small-post {
|
||||
grid-column: span 1;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<Nav />
|
||||
|
||||
<div class="wrapper">
|
||||
<div class="grid">
|
||||
<div class="big-post"><BigPost postId={12345} /></div>
|
||||
|
||||
<div class="medium-post"><MediumPost postId={12345} /></div>
|
||||
<div class="medium-post"><MediumPost postId={12345} /></div>
|
||||
|
||||
<div class="small-post"><SmallPost postId={12345} /></div>
|
||||
<div class="small-post"><SmallPost postId={12345} /></div>
|
||||
<div class="small-post"><SmallPost postId={12345} /></div>
|
||||
<div class="small-post"><SmallPost postId={12345} /></div>
|
||||
<div class="small-post"><SmallPost postId={12345} /></div>
|
||||
<div class="small-post"><SmallPost postId={12345} /></div>
|
||||
<div class="small-post"><SmallPost postId={12345} /></div>
|
||||
<div class="small-post"><SmallPost postId={12345} /></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Footer />
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
Getting over that this is more code, it's actually a much cleaner separation. What was a four-component layout is now managed 100% within the top-level `index.astro` (which we can now consider a **Layout Component**, and if we wanted to reuse this we could extract this into its own file). Your layout is centralized, and now these components truly are reusable because they don't care one bit about whether they're in the same grid or not. You can edit styles in any of these files now without fear of styles breaking in another.
|
||||
|
||||
The basic rule is that when orchestrating multiple components, **that's a unique responsibility** that should live in one central place, rather than split between 4 components as we were doing. In fact, top-level pages are great at this, and should always be the starting point of your layout components. See how far you can take it, and only extract layout components when you absolutely have to.
|
||||
|
||||
To recap: **if you have to touch multiple files to manage one layout, you probably need to reorganize everything into a Layout Component.**
|
||||
|
||||
💁 **Why this works well in Astro**: In Astro, anything can be a `.astro` component, and you never incur performance problems no matter how many components you add. But the main benefit to [Layout isolation][layout-isolated] is how much it cuts down on the amount of CSS you need.
|
||||
|
||||
#### Suggestion #2: Avoid Flexbox and Grid libraries (write your own!)
|
||||
|
||||
This may feel like a complete overreach to tell you not to use your favorite layout framework you're familiar with. After all, it's gotten you this far! But the days of [float madness](https://zellwk.com/blog/responsive-grid-system/) are gone, replaced by Flexbox and Grid. And the latter don't need libraries to manage them (often they can make it harder).
|
||||
|
||||
Many front-end developers experience the following train of thought:
|
||||
|
||||
1. I should reuse as much CSS as possible (_good!_)
|
||||
2. Many pages reuse the same layout, … (_hold up—_)
|
||||
3. … therefore I can find an existing solution to manage all my duplicate layouts (_wait a minute—_)
|
||||
|
||||
While the logic is sound, the reality is that #2 isn't truth for many projects. Probably, many parts of the website weren't designed to fit into these nice, neat, 12 column grids. Even modest web apps can contain _hundreds_ of unique layouts when you factor in all the breakpoints. Ask yourself: _If the website I'm building really contains so many unique layouts, why am I using a heavy grid library that only gives me generic layouts?_
|
||||
|
||||
A few well-written lines of CSS Grid here and there will not only be perfect in every occasion; it's likely lighter and easier to manage than that heavy library you've fought with for so long. Another way to look at it: if you have to spend a couple hours learning a proprietary styling framework, wrestling with it, filing issues, etc., why not just spend that time on Flexbox and Grid instead? For many people, learning the basics only takes an hour, and that can get you pretty far! There are great, free, learning resources that are worth your time:
|
||||
|
||||
- [Flexbox Froggy](https://flexboxfroggy.com/)
|
||||
- [CSS Grid Garden](https://cssgridgarden.com/)
|
||||
|
||||
So in short: stop trying to deduplicate layouts when there's nothing to deduplicate! You'll find your styles not only easier to manage, but your CSS payloads much lighter, and load times faster.
|
||||
|
||||
💁 **Why this works well in Astro**: grid libraries are a quick path to stylesheet bloat, and a major contributor to people attempting to [treeshake their styles][css-treeshaking]. Astro does **not** treeshake unused CSS for you, because [that can cause problems][css-treeshaking]. We're not saying you have to be library free; we're big fans of libraries like [Material UI][material-ui]. But if you can at least shed the thousands upon thousands of layouts you're not using from your styling library, you probably don't need automatic treeshaking.
|
||||
|
||||
#### Suggestion #3: Avoid `margin` on a component wrapper
|
||||
|
||||
In other words, don't do this:
|
||||
|
||||
```jsx
|
||||
<!-- src/components/MyComponent.astro -->
|
||||
<style lang="scss">
|
||||
.wrapper {
|
||||
/* ❌ Don't do this! */
|
||||
margin-top: 3rem;
|
||||
}
|
||||
</style>
|
||||
|
||||
<div class="wrapper"></div>
|
||||
```
|
||||
|
||||
If you remember the [CSS box model][box-model], `margin` extends beyond the boundaries of the box. This means that when you place `margin` on the outermost element, now that will push other components next to it. Even though the styles are scoped, it's _technically_ affecting elements around it, so it [breaks the concept of style containment][layout-isolated].
|
||||
|
||||
When you have components that rearrange, or appear different when they're next to other components, that's a hard battle to win. **Components should look and act the same no matter where they are placed.** That's what makes them components!
|
||||
|
||||
💁 **Why this works well in Astro**: margins pushing other components around creeps into your styling architecture in sneaky ways, and can result in the creation of some wonky or brittle layout components. Avoiding it altogether will keep your layout components simpler, and you'll spend less time styling in general.
|
||||
|
||||
#### Suggestion #4: Avoid global media queries
|
||||
|
||||
The final point is a natural boundary of **Scoped Styles**. That extends to breakpoints, too! You know that one, weird breakpoint where your `<Card />` component wraps awkwardly at a certain size? You should handle that within `<Card />`, and not anywhere else.
|
||||
|
||||
Even if you end up with some random value like `@media (min-width: 732px) {`, that'll probably work better than trying to create a global [magic number][magic-number] somewhere that only applies to one context (an arbitrary value may be "magic" to the rest of an app, but it does still have meaning within the context of a component that needs that specific value).
|
||||
|
||||
Granted, this has been near-impossible to achieve until Container Queries; fortunately [they are finally landing!][container-queries]
|
||||
|
||||
Also, a common complaint of this approach is when someone asks _"What if I have 2 components that need to do the same thing at the same breakpoint?"_ to which my answer is: you'll always have one or two of those; just handle those as edge cases. But if your entire app is made up of dozens of these cases, perhaps your component lines could be redrawn so that they're more [layout-isolated][layout-isolated] in general.
|
||||
|
||||
💁 **Why this works well in Astro**: this is probably the least important point, which is why it's saved for last. In fact, you could probably skip this if it doesn't work for you. But it's something that people try to architect for at scale, and having a global system to manage this can often be unnecessary. Give _not_ architecting for global media queries a try, and see how far it takes you!
|
||||
|
||||
### 👓 Further Reading
|
||||
|
||||
This guide wouldn't be possible without the following blog posts, which expand on these topics and explain them in more detail. Please give them a read!
|
||||
|
||||
- [**Layout-isolated Components**][layout-isolated] by Emil Sjölander
|
||||
- [**In defense of utility-first CSS**][utility-css] by Sarah Dayan
|
||||
|
||||
Also please check out the [Stylelint][stylelint] project to whip your styles into shape. You lint your JS, why not your CSS?
|
||||
|
||||
[autoprefixer]: https://github.com/postcss/autoprefixer
|
||||
[bem]: http://getbem.com/introduction/
|
||||
[box-model]: https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/The_box_model
|
||||
[browserslist]: https://github.com/browserslist/browserslist
|
||||
[browserslist-defaults]: https://github.com/browserslist/browserslist#queries
|
||||
[cassie-evans-css]: https://twitter.com/cassiecodes/status/1392756828786790400?s=20
|
||||
[container-queries]: https://ishadeed.com/article/say-hello-to-css-container-queries/
|
||||
[css-modules]: https://github.com/css-modules/css-modules
|
||||
[css-treeshaking]: https://css-tricks.com/how-do-you-remove-unused-css-from-a-site/
|
||||
[fouc]: https://en.wikipedia.org/wiki/Flash_of_unstyled_content
|
||||
[layout-isolated]: https://web.archive.org/web/20210227162315/https://visly.app/blogposts/layout-isolated-components
|
||||
[issues]: https://github.com/snowpackjs/astro/issues
|
||||
[magic-number]: https://css-tricks.com/magic-numbers-in-css/
|
||||
[material-ui]: https://material.io/components
|
||||
[peace-on-css]: https://didoo.medium.com/let-there-be-peace-on-css-8b26829f1be0
|
||||
[sass]: https://sass-lang.com/
|
||||
[sass-use]: https://sass-lang.com/documentation/at-rules/use
|
||||
[smacss]: http://smacss.com/
|
||||
[styled-components]: https://styled-components.com/
|
||||
[styled-jsx]: https://github.com/vercel/styled-jsx
|
||||
[stylelint]: https://stylelint.io/
|
||||
[svelte-style]: https://svelte.dev/docs#style
|
||||
[tailwind]: https://tailwindcss.com
|
||||
[tailwind-utilities]: https://tailwindcss.com/docs/adding-new-utilities#using-css
|
||||
[utility-css]: https://frontstuff.io/in-defense-of-utility-first-css
|
||||
[vue-css-modules]: https://vue-loader.vuejs.org/guide/css-modules.html
|
||||
[vue-scoped]: https://vue-loader.vuejs.org/guide/scoped-css.html
|
21
docs/src/pages/group-10/index.astro
Normal file
21
docs/src/pages/group-10/index.astro
Normal file
|
@ -0,0 +1,21 @@
|
|||
---
|
||||
import Layout from '../../layouts/MainLayout.astro';
|
||||
---
|
||||
|
||||
<script>
|
||||
// This is some wip redirect code based on the browser language.
|
||||
// A vercel.json redirect is enforced in production, so no user should ever see this page.
|
||||
// Remove the vercel.json redirect when this is ready.
|
||||
const KNOWN_LANGUAGES = ['de','en','es','fi','nl','pt-br','zh-CN','zh-TW'];
|
||||
let newLangWithRegion = (window.navigator.userLanguage || window.navigator.language || 'en-US').substr(0, 5);
|
||||
let newLang = newLangWithRegion.substr(0, 2);
|
||||
if (newLang === 'en') {
|
||||
window.location.pathname = '/getting-started';
|
||||
} else if (KNOWN_LANGUAGES.includes(newLangWithRegion)) {
|
||||
window.location.pathname = '/' + newLangWithRegion + '/getting-started';
|
||||
} else if (KNOWN_LANGUAGES.includes(newLang)) {
|
||||
window.location.pathname = '/' + newLang + '/getting-started';
|
||||
} else {
|
||||
window.location.pathname = '/getting-started';
|
||||
}
|
||||
</script>
|
161
docs/src/pages/group-10/installation.md
Normal file
161
docs/src/pages/group-10/installation.md
Normal file
|
@ -0,0 +1,161 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Installation
|
||||
---
|
||||
|
||||
There are a few different ways to install Astro in a new project.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- **Node.js** - `v12.20.0`, `v14.13.1`, `v16.0.0`, or higher.
|
||||
- **Text editor** - We recommend [VS Code](https://code.visualstudio.com/) with our [Official Astro extension](https://marketplace.visualstudio.com/items?itemName=astro-build.astro-vscode).
|
||||
- **Terminal** - Astro is mainly accessed via the terminal's command-line.
|
||||
|
||||
For demonstration purposes, we will be using [`npm`](https://www.npmjs.com/) in the examples below, but you could also use [`yarn`](https://yarnpkg.com/) or [`pnpm`](https://pnpm.io/) if you prefer an npm alternative.
|
||||
|
||||
## Create Astro
|
||||
|
||||
`npm init astro` is the easiest way to install Astro in a new project. Run this command in your terminal to start our `create-astro` install wizard to assist you with setting up a new project.
|
||||
|
||||
```shell
|
||||
# With NPM
|
||||
npm init astro
|
||||
|
||||
# Yarn
|
||||
yarn create astro
|
||||
```
|
||||
|
||||
[`create-astro`](https://github.com/snowpackjs/astro/tree/main/packages/create-astro) wizard lets you choose from a set of [starter templates](/examples) or alternatively, you could import your own Astro project directly from Github.
|
||||
|
||||
```bash
|
||||
# Note: Replace "my-astro-project" with the name of your project.
|
||||
|
||||
# npm 6.x
|
||||
npm init astro my-astro-project --template starter
|
||||
# npm 7+ (extra double-dash is needed)
|
||||
npm init astro my-astro-project -- --template starter
|
||||
# yarn
|
||||
yarn create astro my-astro-project --template starter
|
||||
# Using a third-party template
|
||||
npm init astro my-astro-project -- --template [GITHUB_USER]/[REPO_NAME]
|
||||
# Using a third-party template, inside a repo
|
||||
npm init astro my-astro-project -- --template [GITHUB_USER]/[REPO_NAME]/path/to/template
|
||||
```
|
||||
|
||||
After `create-astro` scaffolds out your project, remember to install your projects dependencies using npm or your package manager of choice. In this example, we'll use npm:
|
||||
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
You can now [Start](#start-astro) your Astro project. Once you have completed assembling your Astro project you can then [Build](#build-astro) your project. Astro would then package up your application and have the static files ready for you to [Deploy](/guides/deploy) to your favourite hosting provider
|
||||
|
||||
## Manual Install
|
||||
|
||||
You can also setup Astro without the aide of the `create-astro` wizard, below are the few extra steps that are required to get Astro going.
|
||||
|
||||
### Set up your project
|
||||
|
||||
```bash
|
||||
# Make and enter a new directory
|
||||
mkdir my-astro-project
|
||||
cd my-astro-project
|
||||
```
|
||||
|
||||
Create an empty directory with the name of your project, and then navigate into it:
|
||||
|
||||
### Create `package.json`
|
||||
|
||||
```bash
|
||||
# This command will create a basic package.json for you
|
||||
npm init --yes
|
||||
```
|
||||
|
||||
Astro is designed to work with the entirety of the npm package ecosystem. This is managed by a project manifest at the root of your project known as `package.json` . If you're not familiar with the `package.json` file, we highly recommend you to have a quick read over it on [the npm documentation](https://docs.npmjs.com/creating-a-package-json-file).
|
||||
|
||||
### Install Astro
|
||||
|
||||
Following the instructions above, you should have a directory with a single `package.json` file inside of it. You can now setup Astro inside your project.
|
||||
|
||||
```bash
|
||||
npm install astro
|
||||
```
|
||||
|
||||
You can now replace the placeholder "scripts" section of your `package.json` file that `npm init` created for you with the following:
|
||||
|
||||
```diff
|
||||
"scripts": {
|
||||
- "test": "echo \"Error: no test specified\" && exit 1"
|
||||
+ "start": "astro dev",
|
||||
+ "build": "astro build"
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
The [`start`](#start-astro) command launches the Astro Dev Server on `http://localhost:3000`. Once your project is ready, the [`build`](#build-astro) command outputs your project to the `dist/` directory. [Read more about deploying Astro in the Deploy guide.](/guides/deploy)
|
||||
|
||||
### Create your first page
|
||||
|
||||
Astro Open up your favourite text editor, and create a new file in your project:
|
||||
|
||||
1. Create a new file at `src/pages/index.astro`
|
||||
2. Copy-and-paste the following snippet (including `---` dashes) into it.
|
||||
|
||||
```astro
|
||||
---
|
||||
// JS/TS Code written in between the (---) code fence,
|
||||
// is ran solely on the Server!
|
||||
console.log('See me in the Terminal')
|
||||
---
|
||||
|
||||
<html>
|
||||
<body>
|
||||
<h1>Hello, World!</h1>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
<style lang='css||scss'>
|
||||
body{
|
||||
h1{
|
||||
color:orange;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<script>
|
||||
// JS Code entered here is ran entirely on the Browser
|
||||
console.log('See me in the devTools')
|
||||
</script>
|
||||
```
|
||||
|
||||
Above is an example of the Astro's Component's Syntax, which comprises of both HTML & JSX.
|
||||
|
||||
You can create more pages in the `src/pages` directory, and Astro will use the filename to create new pages on your site. For example, by creating a new file at `src/pages/about.astro` (reusing the previous snippet), Astro will generate a new page at the URL : `http://localhost/about`
|
||||
|
||||
## [Start Astro](#start-astro)
|
||||
|
||||
```bash
|
||||
npm start
|
||||
```
|
||||
|
||||
Astro will now start serving your application on `http://localhost:3000`. By opening this URL in your browser, you should see the Astro's “Hello, World”
|
||||
|
||||
## [Build Astro](#build-astro)
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
This will instruct Astro to build your site and save it directly to disk. Your application is now ready in the `dist/` directory.
|
||||
|
||||
## Next Steps
|
||||
|
||||
Success! You're now ready to start developing!
|
||||
|
||||
We highly encourage you to get more familiar with the way Astro works. You can do so by further exploring our Docs, we suggest that you consider the following:
|
||||
|
||||
📚 Learn more about Astro's project structure in our [Project Structure guide.](/core-concepts/project-structure)
|
||||
|
||||
📚 Learn more about Astro's component syntax in our [Astro Components guide.](/core-concepts/astro-components)
|
||||
|
||||
📚 Learn more about Astro's file-based routing in our [Routing guide.](core-concepts/astro-pages)
|
60
docs/src/pages/group-10/nl/getting-started.md
Normal file
60
docs/src/pages/group-10/nl/getting-started.md
Normal file
|
@ -0,0 +1,60 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Beginnen
|
||||
lang: nl
|
||||
---
|
||||
|
||||
Astro is een moderne statische sitebouwer. Leer alles over Astro op onze [homepage](https://astro.build/) of ons [release-bericht](https://astro.build/blog/introducing-astro). Deze pagina is een overzicht van de Astro documentatie en alle gerelateerde bronnen.
|
||||
|
||||
Benieuwd naar een snel overzicht van wat Astro is? [Bezoek onze homepage.](https://astro.build)
|
||||
|
||||
## Probeer Astro
|
||||
|
||||
De gemakkelijkste manier om Astro te proberen, is door `npm init astro` uit te voeren in een nieuwe map op je computer. Deze CLI odpracht helpt je in verschillende stappen je eerste Astro project op te zetten.
|
||||
|
||||
Lees onze [installatiegids](/installation) voor een volledige uitleg over hoe u met Astro aan de slag kunt.
|
||||
|
||||
### Online Playgrounds
|
||||
|
||||
Als je interesse hebt om Astro online uit te proberen in je browser, kun je de een online playground gebruiken. Probeer een Hello World voorbeeld op [CodeSandbox](https://codesandbox.io/s/astro-template-hugb3).
|
||||
|
||||
_Opmerking: sommige functies (bv. Snel vernieuwen) zijn momenteel beperk op CodeSandbox._
|
||||
|
||||
## Astor leren
|
||||
|
||||
Mensen komen naar Astro vanuit verschillende achtergronden en met verschillende leerstijlen. Of u nu de voorkeur geeft aan een meer theoretische of praktische benadering, we hopen dat je deze sectie nuttig zult vinden.
|
||||
|
||||
- Als je liever **leert door te doen**, begin dan met onze [voorbeeldenbibliotheek](https://github.com/snowpackjs/astro/tree/main/examples).
|
||||
- Als u de concepten liever **stap voor stap leert**, begin dan met onze [basisconcepten en handleidingen](/core-concepts/project-structure).
|
||||
|
||||
Zoals elke onbekende technologie heeft Astro een leercurve. Met wat oefening en wat geduld krijg je het onder de knie.
|
||||
|
||||
### Leer de `.astro` syntax
|
||||
|
||||
Wanneer u Astro begint te leren, zult u veel bestanden zien die de `.astro` bestandsextensie gebruiken. Dit is de syntax van de **Astro-component**: een speciaal HTML-achtig bestandsformaat dat Astro gebruikt voor sjablonen. Het is ontworpen om vertrouwd te voelen voor iedereen met HTML- of JSX-ervaring.
|
||||
|
||||
Onze gids over [Astro-componenten](/core-concepts/astro-components) helpt je door de nieuwe `.astro` syntax en is de beste manier om te leren.
|
||||
|
||||
### API referentie
|
||||
|
||||
Deze documentatiesectie is handig als je meer details wilt weten over een bepaalde Astro API. [Configuratie referentie](/reference/configuration-reference) vermeldt bijvoorbeeld alle mogelijke configuratieopties die beschikbaar zijn. [Ingebouwde Componenten Referentie](/reference/builtin-components) geeft een overzicht van alle beschikbare kerncomponenten, zoals <Markdown /> en <Prism />.
|
||||
|
||||
### Documentatie versies
|
||||
|
||||
Deze documentatie geeft altijd de laatste stabiele versie van Astro weer. Zodra we de v1.0-mijlpaal hebben bereikt, voegen we de mogelijkheid toe om versiedocumentatie te bekijken.
|
||||
|
||||
## Op de hoogte blijven
|
||||
|
||||
Het [@astrodotbuild](https://twitter.com/astrodotbuild) Twitter-account is de officiële bron voor de updates van het Astro-team.
|
||||
|
||||
We plaatsen ook release-aankondigingen in onze [Discord-community](https://astro.build/chat) in het #announcements kanaal.
|
||||
|
||||
Niet elke Astro-release verdient een eigen blogpost, maar je kunt een gedetailleerde changelog voor elke release vinden in het [CHANGELOG.md-bestand in de Astro-repository](https://github.com/snowpackjs/astro/blob/main/packages/astro/CHANGELOG.md).
|
||||
|
||||
## Mis je iets?
|
||||
|
||||
Als er iets ontbreekt in de documentatie of als je een onderdeel verwarrend vond, [dien dan een probleem in voor de documentatie](https://github.com/snowpackjs/astro/issues/new/choose) met je suggesties voor verbetering, of tweet naar het [@astrodotbuild](https://twitter.com/astrodotbuild) Twitter-account. We horen graag van je!
|
||||
|
||||
## Credit
|
||||
|
||||
Deze handleiding 'Aan de slag' was oorspronkelijk gebaseerd op de handleiding 'Aan de slag' van [React](https://reactjs.org/).
|
62
docs/src/pages/group-10/pt-br/getting-started.md
Normal file
62
docs/src/pages/group-10/pt-br/getting-started.md
Normal file
|
@ -0,0 +1,62 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Introdução
|
||||
lang: pt-br
|
||||
---
|
||||
|
||||
Astro é um moderno construtor de site estático. Aprenda mais sobre Astro através da [nossa página inicial](https://astro.build/) ou do [nosso post de lançamento](https://astro.build/blog/introducing-astro). Esta página é uma visão geral da documentação do Astro e de todos os recursos relacionados.
|
||||
|
||||
Procurando por uma visão rápida do que é Astro? [Visite nossa página inicial.](https://astro.build)
|
||||
|
||||
## Experimente Astro
|
||||
|
||||
A maneira mais fácil de experimentar Astro é através da execução do comando `npm init astro` em um novo diretório na sua máquina. Nosso assistente para interface de linha de comandos (Wizard CLI) irá te ajudar a iniciar um novo projeto Astro.
|
||||
|
||||
Para começar com Astro em 5 etapas rápidas e fáceis, visite nosso [Guia de início rápido](quick-start).
|
||||
|
||||
Como alternativa, leia nosso [Guia de Instalação](/installation) para uma guia de instalação completo do Astro.
|
||||
|
||||
### Experimente Online
|
||||
|
||||
Se você tem interesse em testar Astro online no navegador, você pode usar um editor de código online. Experimente nosso template "Olá Mundo!" em [CodeSandbox](https://codesandbox.io/s/astro-template-hugb3).
|
||||
|
||||
_Nota: algumas funcionalidades (ex: Fast Refresh) no momento estão limitadas no CodeSandbox._
|
||||
|
||||
## Aprenda Astro
|
||||
|
||||
Todos os tipos de pessoas vêm ao Astro com diferentes bagagens trazendo com eles diferentes estilos de aprendizagem. Se você prefere uma abordagem mais teórica ou prática, esperamos que você encontre esta seção útil.
|
||||
|
||||
- Se você prefere **aprender fazendo**, comece com nossa [biblioteca de exemplos](https://github.com/snowpackjs/astro/tree/main/examples).
|
||||
- Se você prefere **aprender conceitos passo-a-passo**, comece com [conceitos básicos e guias](/core-concepts/project-structure).
|
||||
|
||||
Como qualquer tecnologia emergente, Astro vem com uma leve curva de aprendizado. No entanto, com prática e alguma paciência, sabemos que você _vai_ pegar o jeito da coisa.
|
||||
|
||||
### Aprenda a Sintaxe do `.astro`
|
||||
|
||||
Quando você começa a aprender Astro, você verá muitos arquivos usando a extensão `.astro`. Esta é a **Sintaxe de componentes do Astro**: um formato de arquivo HTML especial que o Astro usa para modelagem. Foi projetado para dar o sentimento de familiaridade para qualquer pessoa com experiência HTML ou JSX.
|
||||
|
||||
Nosso guia útil em [componentes Astro](/core-concepts/astro-components) apresenta você à sintaxe Astro e é a melhor maneira de aprender.
|
||||
|
||||
### Referência da API
|
||||
|
||||
Esta seção de documentação é útil quando você deseja aprender mais detalhes sobre uma determinada API do Astro. Por exemplo, [Referência de Configuração](/reference/configuration-reference) lista todas as opções de configuração possíveis disponíveis para você. [Referência de componentes incorporados](/reference/builtin-components) listas todos os componentes base disponíveis, como `<Markdown />` e `<Prism />`.s
|
||||
|
||||
### Documentação por Versão
|
||||
|
||||
Esta documentação sempre reflete a última versão estável do Astro. Assim que liberarmos a versão v1.0, adicionaremos a capacidade de visualizar a documentação baseado na versão.
|
||||
|
||||
## Fique Informado(a)
|
||||
|
||||
A conta do Twitter [@astrodotbuild](https://twitter.com/astrodotbuild) é a fonte oficial de atualizações da equipe do Astro.
|
||||
|
||||
Também publicamos anúncios de lançamento em nossa [comunidade no Discord](https://astro.build/chat) no canal #announcements.
|
||||
|
||||
Nem todo lançamento do Astro merece sua própria postagem no blog, mas você pode encontrar um changelog detalhado para cada lançamento no arquivo [`CHANGELOG.md` no repositório Astro](https://github.com/snowpackjs/astro/blob/main/packages/astro/CHANGELOG.md).
|
||||
|
||||
## Algo está faltando?
|
||||
|
||||
Se algo estiver faltando na documentação ou se você achar alguma parte confusa, por favor [registre uma nova issue para a documentação](https://github.com/snowpackjs/astro/issues/new/choose) com suas sugestões de melhoria, ou tweet na conta do Twitter [@astrodotbuild](https://twitter.com/astrodotbuild). Nós adoramos ouvir de você!
|
||||
|
||||
## Créditos
|
||||
|
||||
Este guia de introdução foi originalmente baseado no guia de introdução do [React](https://reactjs.org/).
|
70
docs/src/pages/group-10/quick-start.md
Normal file
70
docs/src/pages/group-10/quick-start.md
Normal file
|
@ -0,0 +1,70 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Quick Start
|
||||
---
|
||||
|
||||
```shell
|
||||
# prerequisite: check that Node.js is 12.20.0+, 14.13.1+, or 16+
|
||||
node --version
|
||||
|
||||
# Make a new project directory, and navigate directly into it
|
||||
mkdir my-astro-project && cd $_
|
||||
|
||||
# prepare for liftoff...
|
||||
npm init astro
|
||||
|
||||
# install dependencies
|
||||
npm install
|
||||
|
||||
# start developing!
|
||||
npm start
|
||||
|
||||
# when you're ready: build your static site to `dist/`
|
||||
npm run build
|
||||
```
|
||||
|
||||
If you wish to learn more about the range of methods to install and setup Astro for your project's, please [read our installation guide.](installation)
|
||||
|
||||
## Start your project
|
||||
|
||||
From inside your project directory, enter the following command into your terminal:
|
||||
|
||||
```bash
|
||||
npm start
|
||||
```
|
||||
|
||||
Astro will now start serving your application on [http://localhost:3000](http://localhost:3000). Opening this URL in your browser, you should see the Astro's "Hello, World".
|
||||
|
||||
The server will listen for live file changes in your `src/` directory, so you do not need to restart the application as you make changes during development.
|
||||
|
||||
## Build your project
|
||||
|
||||
To build your project, from inside your directory enter the following build command into your terminal:
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
This will instruct Astro to build your site and save it directly to disk. Your application is now ready in the `dist/` directory.
|
||||
|
||||
## Deploy your project
|
||||
|
||||
Astro sites are static, so they can be deployed to your favourite host:
|
||||
|
||||
- [Vercel](https://vercel.com/)
|
||||
- [Netlify](https://www.netlify.com/)
|
||||
- [S3 bucket](https://aws.amazon.com/s3/)
|
||||
- [Google Firebase](https://firebase.google.com/)
|
||||
- [Read more about deploying Astro in our Deploy guide.](/guides/deploy)
|
||||
|
||||
## Next Steps
|
||||
|
||||
Success! You're now ready to start developing!
|
||||
|
||||
We recommend that you to take some time to get more familiar with the way Astro works. You can do so by further exploring our Docs, we suggest that you consider the following:
|
||||
|
||||
📚 Learn more about Astro's project structure in our [Project Structure guide.](/core-concepts/project-structure)
|
||||
|
||||
📚 Learn more about Astro's component syntax in our [Astro Components guide.](/core-concepts/astro-components)
|
||||
|
||||
📚 Learn more about Astro's file-based routing in our [Routing guide.](core-concepts/astro-pages)
|
196
docs/src/pages/group-10/reference/api-reference.md
Normal file
196
docs/src/pages/group-10/reference/api-reference.md
Normal file
|
@ -0,0 +1,196 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: API Reference
|
||||
---
|
||||
|
||||
## `Astro` global
|
||||
|
||||
The `Astro` global is available in all contexts in `.astro` files. It has the following functions:
|
||||
|
||||
### `Astro.fetchContent()`
|
||||
|
||||
`Astro.fetchContent()` is a way to load local `*.md` files into your static site setup. You can either use this on its own, or within [Astro Collections](/core-concepts/collections).
|
||||
|
||||
```jsx
|
||||
// ./src/components/my-component.astro
|
||||
---
|
||||
const data = Astro.fetchContent('../pages/post/*.md'); // returns an array of posts that live at ./src/pages/post/*.md
|
||||
---
|
||||
|
||||
<div>
|
||||
{data.slice(0, 3).map((post) => (
|
||||
<article>
|
||||
<h1>{post.title}</h1>
|
||||
<p>{post.description}</p>
|
||||
<a href={post.url}>Read more</a>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
```
|
||||
|
||||
`.fetchContent()` only takes one parameter: a relative URL glob of which local files you'd like to import. Currently only `*.md` files are supported. It's synchronous, and returns an array of items of type:
|
||||
|
||||
```js
|
||||
{
|
||||
/** frontmatter from the post.. example frontmatter:
|
||||
title: '',
|
||||
tag: '',
|
||||
date: '',
|
||||
image: '',
|
||||
author: '',
|
||||
description: '',
|
||||
**/
|
||||
astro: {
|
||||
headers: [], // an array of h1...h6 elements in the markdown file
|
||||
source: '' // raw source of the markdown file
|
||||
html: '' // rendered HTML of the markdown file
|
||||
},
|
||||
url: '' // the rendered path
|
||||
}[]
|
||||
```
|
||||
|
||||
### `Astro.request`
|
||||
|
||||
`Astro.request` returns an object with the following properties:
|
||||
|
||||
| Name | Type | Description |
|
||||
| :------------- | :---- | :---------------------------------------------- |
|
||||
| `url` | `URL` | The URL of the request being rendered. |
|
||||
| `canonicalURL` | `URL` | [Canonical URL][canonical] of the current page. |
|
||||
|
||||
⚠️ Temporary restriction: this is only accessible in top-level pages and not in sub-components.
|
||||
|
||||
### `Astro.site`
|
||||
|
||||
`Astro.site` returns a `URL` made from `buildOptions.site` in your Astro config. If undefined, this will return a URL generated from `localhost`.
|
||||
|
||||
## Collections API
|
||||
|
||||
A collection is any file in the `src/pages` directory that starts with a dollar sign (`$`) and includes an exported `createCollection` function in the component script.
|
||||
|
||||
Check out our [Astro Collections](/core-concepts/collections) guide for more information and examples.
|
||||
|
||||
### `createCollection()`
|
||||
|
||||
```jsx
|
||||
---
|
||||
export async function createCollection() {
|
||||
return { /* ... */ };
|
||||
}
|
||||
---
|
||||
<!-- Your HTML template here. -->
|
||||
```
|
||||
|
||||
⚠️ The `createCollection()` function executes in its own isolated scope before page loads. Therefore you can't reference anything from its parent scope, other than file imports. The compiler will warn if you break this requirement.
|
||||
|
||||
The `createCollection()` function should returns an object of the following shape:
|
||||
|
||||
| Name | Type | Description |
|
||||
| :--------- | :--------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `route` | `string` | **Required.** A route pattern for matching URL requests. This is used to generate the page URL in your final build. It must begin with the file name: for example, `pages/$tags.astro` must return a `route` that starts with `/tags/`. |
|
||||
| `paths` | `{params: Params}[]` | Return an array of all URL to be generated. |
|
||||
| `props` | `async ({ params, paginate }) => object` | **Required.** Load data for the page that will get passed to the page component as props. |
|
||||
| `paginate` | `boolean` | Optional: Enable automatic pagination. See next section. |
|
||||
| `rss` | [RSS](/reference/api-reference#rss-feed) | Optional: generate an RSS 2.0 feed from this collection ([docs](/reference/api-reference#rss-feed)) |
|
||||
|
||||
### Pagination
|
||||
|
||||
Enable pagination for a collection by returning `paginate: true` from `createCollection()`. This passes a `paginate()` argument to `props()` that you can use to return paginated data in your HTML template via props.
|
||||
|
||||
The `paginate()` function that you use inside of `props()` has the following interface:
|
||||
|
||||
```ts
|
||||
/* the "paginate()" passed to props({paginate}) */
|
||||
type PaginateFunction = (
|
||||
data: any[],
|
||||
args?: {
|
||||
/* pageSize: set the number of items to be shown on every page. Defaults to 10. */
|
||||
pageSize?: number;
|
||||
}
|
||||
) => PaginatedCollectionResult;
|
||||
|
||||
/* the paginated return value, aka the prop passed to every page in the collection. */
|
||||
interface PaginatedCollectionResult {
|
||||
/** result */
|
||||
data: any[];
|
||||
|
||||
/** metadata */
|
||||
/** the count of the first item on the page, starting from 0 */
|
||||
start: number;
|
||||
/** the count of the last item on the page, starting from 0 */
|
||||
end: number;
|
||||
/** total number of results */
|
||||
total: number;
|
||||
page: {
|
||||
/** the current page number, starting from 1 */
|
||||
current: number;
|
||||
/** number of items per page (default: 25) */
|
||||
size: number;
|
||||
/** number of last page */
|
||||
last: number;
|
||||
};
|
||||
url: {
|
||||
/** url of the current page */
|
||||
current: string;
|
||||
/** url of the previous page (if there is one) */
|
||||
prev: string | undefined;
|
||||
/** url of the next page (if there is one) */
|
||||
next: string | undefined;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
📚 Learn more about pagination (and see an example) in our [Astro Collections guide.](/core-concepts/collections).
|
||||
|
||||
### RSS
|
||||
|
||||
Create an RSS 2.0 feed for a collection by returning `paginate: true` & an `rss` object from `createCollection()`. The `rss` object will be used to generate the contents of the RSS XML file.
|
||||
|
||||
The `rss` object follows the `CollectionRSS`data type:
|
||||
|
||||
```ts
|
||||
export interface CollectionRSS<T = any> {
|
||||
/** (required) Title of the RSS Feed */
|
||||
title: string;
|
||||
/** (required) Description of the RSS Feed */
|
||||
description: string;
|
||||
/** Specify arbitrary metadata on opening <xml> tag */
|
||||
xmlns?: Record<string, string>;
|
||||
/** Specify custom data in opening of file */
|
||||
customData?: string;
|
||||
/** Return data about each item */
|
||||
item: (item: T) => {
|
||||
/** (required) Title of item */
|
||||
title: string;
|
||||
/** (required) Link to item */
|
||||
link: string;
|
||||
/** Publication date of item */
|
||||
pubDate?: Date;
|
||||
/** Item description */
|
||||
description?: string;
|
||||
/** Append some other XML-valid data to this item */
|
||||
customData?: string;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
📚 Learn more about RSS feed generation (and see an example) in our [Astro Collections guide.](/core-concepts/collections).
|
||||
|
||||
## `import.meta`
|
||||
|
||||
> In this section we use `[dot]` to mean `.`. This is because of a bug in our build engine that is rewriting `import[dot]meta[dot]env` if we use `.` instead of `[dot]`.
|
||||
|
||||
All ESM modules include a `import.meta` property. Astro adds `import[dot]meta[dot]env` through [Snowpack](https://www.snowpack.dev/).
|
||||
|
||||
**`import[dot]meta[dot]env[dot]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:
|
||||
|
||||
```jsx
|
||||
import { h } from 'preact';
|
||||
|
||||
export default function () {
|
||||
// Note: rewrite "[dot]" to "." for this to to work in your project.
|
||||
return import[dot]meta[dot]env[dot]SSR ? <div class="spinner"></div> : <FancyComponent />;
|
||||
}
|
||||
```
|
||||
|
||||
[canonical]: https://en.wikipedia.org/wiki/Canonical_link_element
|
32
docs/src/pages/group-10/reference/builtin-components.md
Normal file
32
docs/src/pages/group-10/reference/builtin-components.md
Normal file
|
@ -0,0 +1,32 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Built-In Components
|
||||
---
|
||||
|
||||
Astro includes several builtin components for you to use in your projects. All builtin components are available via `import {} from 'astro/components';`.
|
||||
|
||||
## `<Markdown />`
|
||||
|
||||
```astro
|
||||
---
|
||||
import { Markdown } from 'astro/components';
|
||||
---
|
||||
<Markdown>
|
||||
# Markdown syntax is now supported! **Yay!**
|
||||
</Markdown>
|
||||
```
|
||||
|
||||
See our [Markdown Guide](/guides/markdown-content) for more info.
|
||||
|
||||
<!-- TODO: We should move some of the specific component info here. -->
|
||||
|
||||
## `<Prism />`
|
||||
|
||||
```astro
|
||||
---
|
||||
import { Prism } from 'astro/components';
|
||||
---
|
||||
<Prism code={`const foo = 'bar';`} />
|
||||
```
|
||||
|
||||
This component provides syntax highlighting for code blocks. Since this never changes in the client it makes sense to use an Astro component (it's equally reasonable to use a framework component for this kind of thing; Astro is server-only by default for all frameworks!).
|
62
docs/src/pages/group-10/reference/cli-reference.md
Normal file
62
docs/src/pages/group-10/reference/cli-reference.md
Normal file
|
@ -0,0 +1,62 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: CLI Reference
|
||||
---
|
||||
|
||||
## Commands
|
||||
|
||||
### `astro dev`
|
||||
|
||||
Runs the Astro development server. This starts an HTTP server that responds to requests for pages stored in `src/pages` (or which folder is specified in your [configuration](/reference/configuration-reference)).
|
||||
|
||||
See the [dev server](/reference/dev) docs for more information on how the dev server works.
|
||||
|
||||
**Flags**
|
||||
|
||||
#### `--port`
|
||||
|
||||
Specifies should port to run on. Defaults to `3000`.
|
||||
|
||||
### `astro build`
|
||||
|
||||
Builds your site for production.
|
||||
|
||||
## Global Flags
|
||||
|
||||
### `--config path`
|
||||
|
||||
Specify the path to the config file. Defaults to `astro.config.mjs`. Use this if you use a different name for your configuration file or have your config file in another folder.
|
||||
|
||||
```shell
|
||||
astro --config config/astro.config.mjs dev
|
||||
```
|
||||
|
||||
### `--project-root path`
|
||||
|
||||
Specify the path to the project root. If not specified the current working directory is assumed to be the root.
|
||||
|
||||
The root is used for finding the Astro configuration file.
|
||||
|
||||
```shell
|
||||
astro --project-root examples/snowpack dev
|
||||
```
|
||||
|
||||
### `--reload`
|
||||
|
||||
Clears the cache (dependencies are built within Astro apps).
|
||||
|
||||
### `--verbose`
|
||||
|
||||
Enables verbose logging, which is helpful when debugging an issue.
|
||||
|
||||
### `--silent`
|
||||
|
||||
Enables silent logging, which is helpful for when you don't want to see Astro logs.
|
||||
|
||||
### `--version`
|
||||
|
||||
Print the Astro version number and exit.
|
||||
|
||||
### `--help`
|
||||
|
||||
Print the help message and exit.
|
35
docs/src/pages/group-10/reference/configuration-reference.md
Normal file
35
docs/src/pages/group-10/reference/configuration-reference.md
Normal file
|
@ -0,0 +1,35 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: Configuration Reference
|
||||
---
|
||||
|
||||
To configure Astro, add an `astro.config.mjs` file in the root of your project. All settings are optional. Here are the defaults:
|
||||
|
||||
```js
|
||||
export default {
|
||||
projectRoot: '.', // Where to resolve all URLs relative to. Useful if you have a monorepo project.
|
||||
src: './src', // Path to Astro components, pages, and data
|
||||
pages: './src/pages', // Path to Astro/Markdown pages
|
||||
dist: './dist', // When running `astro build`, path to final static output
|
||||
public: './public', // A folder of static files Astro will copy to the root. Useful for favicons, images, and other files that don't need processing.
|
||||
buildOptions: {
|
||||
// site: '', // Your public domain, e.g.: https://my-site.dev/. Used to generate sitemaps and canonical URLs.
|
||||
sitemap: true, // Generate sitemap (set to "false" to disable)
|
||||
},
|
||||
devOptions: {
|
||||
port: 3000, // The port to run the dev server on.
|
||||
// tailwindConfig: '', // Path to tailwind.config.js if used, e.g. './tailwind.config.js'
|
||||
},
|
||||
// component renderers which are enabled by default
|
||||
renderers: [
|
||||
'@astrojs/renderer-svelte',
|
||||
'@astrojs/renderer-vue',
|
||||
'@astrojs/renderer-react',
|
||||
'@astrojs/renderer-preact',
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
## Snowpack Config
|
||||
|
||||
Astro is powered internally by Snowpack. You can configure Snowpack directly by creating a `snowpack.config.mjs` file. See [snowpack.dev](https://www.snowpack.dev/reference/configuration) for full documentation on this file.
|
209
docs/src/pages/group-10/reference/renderer-reference.md
Normal file
209
docs/src/pages/group-10/reference/renderer-reference.md
Normal file
|
@ -0,0 +1,209 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: UI Renderer Reference
|
||||
---
|
||||
|
||||
Astro is designed to support your favorite UI frameworks. [React](https://npm.im/@astrojs/renderer-react), [Svelte](https://npm.im/@astrojs/renderer-svelte), [Vue](https://npm.im/@astrojs/renderer-vue), and [Preact](https://npm.im/@astrojs/renderer-preact) are all built-in to Astro and supported out of the box. No configuration is needed to enable these.
|
||||
|
||||
Internally, each framework is supported via a framework **renderer.** A renderer is a type of Astro plugin that adds support for a framework. Some are built-in, but you can also provide your own third-party renderers to add Astro support for new frameworks.
|
||||
|
||||
## What is a renderer?
|
||||
|
||||
A renderer is an NPM package that has two responsibilities:
|
||||
|
||||
1. _render a component to a static string of HTML_ at build time.
|
||||
2. _rehydrate that HTML to create an interactive component_ on the client.
|
||||
|
||||
Take a look at any one of Astro's built-in [`renderers`](https://github.com/snowpackjs/astro/tree/main/packages/renderers) to see this in action. We'll go into more detail in the following sections.
|
||||
|
||||
## Building Your Own Renderer
|
||||
|
||||
> **Building a renderer?** We'd love for you to contribute renderers for popular frameworks back to the Astro repo. Feel free to open an issue or pull request to discuss.
|
||||
|
||||
A simple renderer only needs a few files:
|
||||
|
||||
```
|
||||
/my-custom-renderer/
|
||||
├── package.json
|
||||
├── index.js
|
||||
├── server.js
|
||||
└── client.js
|
||||
```
|
||||
|
||||
### Package Manifest (`package.json`)
|
||||
|
||||
A renderer should include any framework dependencies as package dependencies. For example, `@astrojs/renderer-react` includes `react` & `react-dom` as dependencies in the `package.json` manifest.
|
||||
|
||||
```js
|
||||
// package.json
|
||||
"name": "@astrojs/renderer-react",
|
||||
"dependencies": {
|
||||
"react": "^17.0.0",
|
||||
"react-dom": "^17.0.0"
|
||||
}
|
||||
```
|
||||
|
||||
This means that Astro users don't need to install the UI framework packages themselves. The renderer is the only package that your users will need to install.
|
||||
|
||||
### Renderer Entrypoint (`index.js`)
|
||||
|
||||
The main entrypoint of a renderer is a simple JS file which exports a manifest for the renderer. The required values are `name`, `server`, and `client`.
|
||||
|
||||
Additionally, this entrypoint can define a [Snowpack plugin](https://www.snowpack.dev/guides/plugins) that should be used to load non-JavaScript files.
|
||||
|
||||
```js
|
||||
export default {
|
||||
name: '@astrojs/renderer-xxx', // the renderer name
|
||||
client: './client.js', // relative path to the client entrypoint
|
||||
server: './server.js', // optional, relative path to the server entrypoint
|
||||
snowpackPlugin: '@snowpack/plugin-xxx', // optional, the name of a snowpack plugin to inject
|
||||
snowpackPluginOptions: { example: true }, // optional, any options to be forwarded to the snowpack plugin
|
||||
knownEntrypoint: ['framework'], // optional, entrypoint modules that will be used by compiled source
|
||||
external: ['dep'] // optional, dependencies that should not be built by snowpack
|
||||
polyfills: ['./shadow-dom-polyfill.js'] // optional, module scripts that should be loaded before client hydration.
|
||||
hydrationPolyfills: ['./hydrate-framework.js'] // optional, polyfills that need to run before hydration ever occurs.
|
||||
jsxImportSource: 'preact', // optional, the name of the library from which JSX is imported
|
||||
jsxTransformOptions: async () => { // optional, a function to transform JSX files
|
||||
const { default: { default: jsx }} = await import('@babel/plugin-transform-react-jsx');
|
||||
return {
|
||||
plugins: [
|
||||
jsx({}, { runtime: 'automatic', importSource: 'preact' })
|
||||
]
|
||||
}
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### JSX Support
|
||||
|
||||
Astro is unique in that it allows you to mix multiple types of JSX/TSX files in a single project. It does this by reading the `jsxImportSource` and `jsxTransformOptions` from renderers and transforming a file with [Babel](https://babeljs.io/).
|
||||
|
||||
#### `jsxImportSource`
|
||||
|
||||
This is the name of your library (for example `preact` or `react` or `solid-js`) which, if encountered in a file, will signal to Astro that this renderer should be used.
|
||||
|
||||
Users may also manually define `/** @jsxImportSource preact */` in to ensure that the file is processed by this renderer (if, for example, the file has no imports).
|
||||
|
||||
#### `jsxTransformOptions`
|
||||
|
||||
This is an `async` function that returns information about how to transform matching JSX files with [Babel](https://babeljs.io/). It supports [`plugins`](https://babeljs.io/docs/en/plugins) or [`presets`](https://babeljs.io/docs/en/presets) to be passed directly to Babel.
|
||||
|
||||
> Keep in mind that this transform doesn't need to handle TSX separately from JSX, Astro handles that for you!
|
||||
|
||||
The arguments passed to `jsxTransformOptions` follow Snowpack's `load()` plugin hook. These allow you to pass separate Babel configurations for various conditions, like if your files should be compiled differently in SSR mode.
|
||||
|
||||
```ts
|
||||
export interface JSXTransformOptions {
|
||||
(context: {
|
||||
/** True if builder is in dev mode (`astro dev`) */
|
||||
isDev: boolean;
|
||||
/** True if HMR is enabled (add any HMR code to the output here). */
|
||||
isHmrEnabled: boolean;
|
||||
/** True if builder is in SSR mode */
|
||||
isSSR: boolean;
|
||||
/** True if file being transformed is inside of a package. */
|
||||
isPackage: boolean;
|
||||
}) => {
|
||||
plugins?: any[];
|
||||
presets?: any[];
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Server Entrypoint (`server.js`)
|
||||
|
||||
The server entrypoint of a renderer is responsible for checking if a component should use this renderer, and if so, how that component should be rendered to a string of static HTML.
|
||||
|
||||
```js
|
||||
export default {
|
||||
// should Component use this renderer?
|
||||
check(Component, props, childHTML) {},
|
||||
// Component => string of static HTML
|
||||
renderToStaticMarkup(Component, props, childHTML) {},
|
||||
};
|
||||
```
|
||||
|
||||
#### `check`
|
||||
|
||||
`check` is a function that determines whether a Component should be "claimed" by this renderer.
|
||||
|
||||
In it's simplest form, it can check for the existence of a flag on Object-based components.
|
||||
|
||||
```js
|
||||
function check(Component) {
|
||||
return Component.isMyFrameworkComponent;
|
||||
}
|
||||
```
|
||||
|
||||
In more complex scenarios, like when a Component is a `Function` without any flags, you may need to use `try/catch` to attempt a full render. This result is cached so that it only runs once per-component.
|
||||
|
||||
```js
|
||||
function check(Component, props, childHTML) {
|
||||
try {
|
||||
const { html } = renderToStaticMarkup(Component, props, childHTML);
|
||||
return Boolean(html);
|
||||
} catch (e) {}
|
||||
return false;
|
||||
}
|
||||
```
|
||||
|
||||
#### `renderToStaticMarkup`
|
||||
|
||||
`renderToStaticMarkup` is a function that renders a Component to a static string of HTML. There's usually a method exported by frameworks named something like `renderToString`.
|
||||
|
||||
```js
|
||||
import { renderToString } from 'xxx';
|
||||
|
||||
function renderToStaticMarkup(Component, props, childHTML) {
|
||||
const html = renderToString(h(Component, { ...props, innerHTML: childHTML }));
|
||||
return { html };
|
||||
}
|
||||
```
|
||||
|
||||
Note that `childHTML` is an HTML string representing this component's children. If your framework does not support rendering HTML directly, you are welcome to use a wrapper component. By convention, Astro uses the `astro-fragment` custom element to inject `childHTML` into. Your renderer should use that, too.
|
||||
|
||||
```js
|
||||
import { h, renderToString } from 'xxx';
|
||||
|
||||
const Wrapper = ({ value }) =>
|
||||
h('astro-fragment', { dangerouslySetInnerHTML: { __html: value } });
|
||||
|
||||
function renderToStaticMarkup(Component, props, childHTML) {
|
||||
const html = renderToString(
|
||||
h(Component, props, h(Wrapper, { value: childHTML }))
|
||||
);
|
||||
return { html };
|
||||
}
|
||||
```
|
||||
|
||||
### Client Entrypoint (`client.js`)
|
||||
|
||||
The client entrypoint of a renderer is responsible for rehydrating static HTML (the result of `renderToStaticMarkup`) back into a fully interactive component. Its `default` export should be a `function` which accepts the host element of the Component, an `astro-root` custom element.
|
||||
|
||||
> If your framework supports non-destructive component hydration (as opposed to a destructive `render` method), be sure to use that! Following your framework's Server Side Rendering (SSR) guide should point you in the right direction.
|
||||
|
||||
```js
|
||||
import { hydrate } from 'xxx';
|
||||
|
||||
export default (element) => {
|
||||
return (Component, props, childHTML) => {
|
||||
hydrate(h(Component, { ...props, innerHTML: childHTML }), element);
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
Note that `childHTML` is an HTML string representing this component's children. If your framework does not support rendering HTML directly, you should use the same wrapper component you used for the server entrypoint.
|
||||
|
||||
```js
|
||||
import { h, hydrate } from 'xxx';
|
||||
import SharedWrapper from './SharedWrapper.js';
|
||||
|
||||
export default (element) => {
|
||||
return (Component, props, childHTML) => {
|
||||
hydrate(
|
||||
h(Component, props, h(SharedWrapper, { value: childHTML })),
|
||||
element
|
||||
);
|
||||
};
|
||||
};
|
||||
```
|
9
docs/src/pages/group-10/zh-CN/examples.md
Normal file
9
docs/src/pages/group-10/zh-CN/examples.md
Normal file
|
@ -0,0 +1,9 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: 模板样例
|
||||
lang: zh-CN
|
||||
---
|
||||
|
||||
如果你喜欢通过实例来学习,请查看我们在 GitHub 上的[模板样例](https://github.com/snowpackjs/astro/tree/main/examples)
|
||||
|
||||
<!-- Once we merge astro-docs back into the main repo, we can actually fetch the list of examples at build-time by scanning the examples/ directory! -->
|
63
docs/src/pages/group-10/zh-CN/getting-started.md
Normal file
63
docs/src/pages/group-10/zh-CN/getting-started.md
Normal file
|
@ -0,0 +1,63 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: 入门指南
|
||||
lang: zh-CN
|
||||
---
|
||||
|
||||
Astro 是一个现代的静态网站生成工具. 你可以从 [我们的主页](https://astro.build/) 或者 [我们的 release 公告](https://astro.build/blog/introducing-astro) 中了解到 Astro 的全部内容,本页是 Astro 文档和所有相关资源的概述。
|
||||
|
||||
想快速了解一下什么是 Astro ? [浏览我们的主页](https://astro.build)
|
||||
|
||||
## 尝试一下 Astro
|
||||
|
||||
尝试 Astro 的最简单的方法是在新目录下运行 `npm init astro`。我们的 CLI 工具会帮助你创建启动一个新的 Astro 项目。
|
||||
|
||||
想要快速了解学习使用 Astro, [快速入门](quick-start).
|
||||
|
||||
另外,请阅读我们的 [安装指南](/installation),了解如何使用 Astro 进行安装的全部步骤。
|
||||
|
||||
### 在线游乐场
|
||||
|
||||
如果你有兴趣在浏览器中尝试 Astro,你可以使用一个在线代码游乐场。试试我们在 [CodeSandbox](https://codesandbox.io/s/astro-template-hugb3) 上的 "Hello World!"模板。
|
||||
|
||||
注意:一些功能(例如:快速刷新)目前在 CodeSandbox 上是受限的。
|
||||
|
||||
## 学习 Astro
|
||||
|
||||
各种各样的人来自不同的背景,带来了不同的学习方式,来到 Astro。无论你喜欢的是理论性强的方法还是实践性强的方法,我们希望你会发现本节内容对你有帮助。
|
||||
|
||||
- 如果你喜欢在**实践中**学习,请从我们的 [实例库](https://github.com/snowpackjs/astro/tree/main/examples) 开始学习。
|
||||
|
||||
- 如果你喜欢**逐步学习概念**,请从我们的[基本概念和指南](/core-concepts/project-structure)开始。
|
||||
|
||||
像任何不熟悉的技术一样,Astro 也有一个轻量化的学习曲线。然而我们相信只要有耐心勤于练习你很快就会掌握诀窍的。
|
||||
|
||||
### 学习 `.astro` 语法
|
||||
|
||||
当你开始学习 Astro 时,你会看到许多文件使用`.astro`文件扩展名。这是**Astro 的组件语法**:一种特殊的类似 HTML 的文件格式,Astro 用于模板制作。这样设计是为了让任何有 HTML 或 JSX 经验的人更容易上手。
|
||||
|
||||
我们在 [Astro 组件](/corecepts/astro-components) 上的有用指南向你介绍了 Astro 语法,这也是学习的最好方法。
|
||||
|
||||
### API 参考文档
|
||||
|
||||
当你想了解某个特定的 Astro API 的更多细节时,这部分文档是有用的。例如 [配置参考](/reference/configuration-reference) 列出所有可能的配置选项供你使用。 [内置组件参考](/reference/builtin-components) 列出了所有可用的核心组件,如`<Markdown />`和`<Prism />`。
|
||||
|
||||
### 其他版本文档
|
||||
|
||||
本文档总是展示 Astro 的最新稳定版本。一旦我们达到 V1.0 的里程碑,我们将增加查看版本文件的能力。
|
||||
|
||||
## 了解最新消息
|
||||
|
||||
[@astrodotbuild](https://twitter.com/astrodotbuild) Twitter 账户是 Astro 团队的官方更新来源。
|
||||
|
||||
我们也在我们的 [Discord 社区](https://astro.build/chat) 的 #announcements 频道中发布 release 公告。
|
||||
|
||||
当然并非每个 Astro 的发布都会有自己的 release 公告,你可以在 Astro 仓库的 [`CHANGELOG.md`文件](https://github.com/snowpackjs/astro/blob/main/packages/astro/CHANGELOG.md) 中找到每个版本的详细更新日志。
|
||||
|
||||
## 勘误与建议
|
||||
|
||||
如果你在阅读的过程中发现文档中缺少什么,或者你发现某些部分令人困惑,请 [为文档提交问题](https://github.com/snowpackjs/astro/issues/new/choose) ,提出你的改进建议,或者在 [@astrodotbuild](https://twitter.com/astrodotbuild) Twitter 账户上发推文。我们希望听到你的建议!
|
||||
|
||||
## 参考
|
||||
|
||||
本入门指南最初是基于 [React](https://reactjs.org/) 的入门指南。
|
170
docs/src/pages/group-10/zh-CN/installation.md
Normal file
170
docs/src/pages/group-10/zh-CN/installation.md
Normal file
|
@ -0,0 +1,170 @@
|
|||
---
|
||||
layout: ~/layouts/MainLayout.astro
|
||||
title: 安装指南
|
||||
lang: zh-CN
|
||||
---
|
||||
|
||||
可以使用多种方式创建 Astro 新项目
|
||||
|
||||
## 环境要求
|
||||
|
||||
- **Node.js** - `v12.20.0`、`v14.13.1` 和 `v16.0.0`,或更高版本。
|
||||
- **文本编辑器** - 我们推荐使用 [VS Code](https://code.visualstudio.com/) 搭配 [Astro 官方插件](https://marketplace.visualstudio.com/items?itemName=astro-build.astro-vscode)。
|
||||
- **命令行终端** - Astro 主要是通过终端的命令行执行。
|
||||
|
||||
下方案例中使用 [`npm`](https://www.npmjs.com/) 为例。也可以使用 [`yarn`](https://yarnpkg.com/) 或 [`pnpm`](https://pnpm.io/) 等 npm 替代方案。
|
||||
|
||||
## 创建 Astro 工程
|
||||
|
||||
`npm init astro` 是在一个新项目中安装 Astro 的最简单的方法。
|
||||
|
||||
在终端运行这个命令,启动我们的 `create-astro` 安装工具,协助你建立一个新项目。
|
||||
|
||||
```shell
|
||||
# 用 NPM
|
||||
npm init astro
|
||||
|
||||
# Yarn
|
||||
yarn create astro
|
||||
```
|
||||
|
||||
[`create-astro`](https://github.com/snowpackjs/astro/tree/main/packages/create-astro) 工具让你从预设的 [启动模板](/examples) 中选择,或者你也可以直接从 Github 导入自己的 Astro 项目。
|
||||
|
||||
```bash
|
||||
# 提醒:把「my-astro-project」改为项目的名称。
|
||||
|
||||
# npm 6.x
|
||||
npm init astro my-astro-project --template starter
|
||||
# npm 7+(一定要多加上一组双横杠)
|
||||
npm init astro my-astro-project -- --template starter
|
||||
# yarn
|
||||
yarn create astro my-astro-project --template starter
|
||||
# 使用第三方模板
|
||||
npm init astro my-astro-project -- --template [GITHUB_USER]/[REPO_NAME]
|
||||
# 在 Repo 里,使用第三方模板
|
||||
npm init astro my-astro-project -- --template [GITHUB_USER]/[REPO_NAME]/path/to/template
|
||||
```
|
||||
|
||||
在 `create-astro` 搭建好你的项目后,记得用 npm 或你选择的软件包管理器安装你的项目依赖。在这个例子中,我们将使用 npm 。
|
||||
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
你现在可以[开发](#start-astro)你的 Astro 项目。一旦你完成了 Astro 项目的开发,你就可以[构建](#build-astro)你的项目。然后 Astro 会把你的应用程序打包,并准备好静态文件,让你[部署](/guides/deploy)到你最喜欢的托管服务商。
|
||||
|
||||
## 手动安装
|
||||
|
||||
当然没有 `create-astro` 工具的协助,也可以创建 Astro 工程。 接下来就是要让 Astro 运行起来的一些额外步骤。
|
||||
|
||||
### 创建项目
|
||||
|
||||
```bash
|
||||
# 创建并进入新项目目录
|
||||
mkdir my-astro-project
|
||||
cd my-astro-project
|
||||
```
|
||||
|
||||
### 创建 `package.json`
|
||||
|
||||
```bash
|
||||
# 初始化项目并生成的默认的 package.json
|
||||
npm init --yes
|
||||
```
|
||||
|
||||
Astro 被设计为与整个 npm 软件包生态系统一起工作。这是由项目根目录下的 `package.json` 管理的。
|
||||
|
||||
如果你不熟悉 `package.json` 文件,我们强烈建议你在[npm 文档](https://docs.npmjs.com/creating-a-package-json-file)上快速阅读它。
|
||||
|
||||
### 安裝 Astro
|
||||
|
||||
按照上面的说明,你的工程目录下会新建一个 `package.json` 文件。
|
||||
|
||||
现在你可以在你的项目中安装 Astro
|
||||
|
||||
```bash
|
||||
npm install astro
|
||||
```
|
||||
|
||||
现在你可以把 `package.json` 文件中默认为你创建的 `scripts` 部分替换为以下内容。
|
||||
|
||||
```diff
|
||||
"scripts": {
|
||||
- "test": "echo \"Error: no test specified\" && exit 1"
|
||||
+ "start": "astro dev",
|
||||
+ "build": "astro build"
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
[`start`](#start-astro) 命令在 `http://localhost:3000` 上启动 Astro 开发服务器。一旦你的项目准备好了。
|
||||
|
||||
[`build`](#build-astro)命令将你的项目输出到 `dist/` 目录。[在部署指南中阅读更多关于部署 Astro 的内容。](/guides/deploy)
|
||||
|
||||
### 创建第一个页面
|
||||
|
||||
打开文本编辑器,在项目添加文件 :
|
||||
|
||||
1. 新建 `src/pages/index.astro` 文件
|
||||
2. 在文件中复制粘贴以下代码片段(包含横杠 "---" )
|
||||
|
||||
```astro
|
||||
---
|
||||
// 在 (`---`) 范围之内的 JS 或 TS 代码只在服务器上运行!
|
||||
console.log('See me in the Terminal')
|
||||
---
|
||||
|
||||
<html>
|
||||
<body>
|
||||
<h1>Hello, World!</h1>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
<style lang='css||scss'>
|
||||
body{
|
||||
h1{
|
||||
color:orange;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
<script>
|
||||
// 在在此输入的JS代码完全在浏览器上运行。
|
||||
console.log('See me in the devTools')
|
||||
</script>
|
||||
```
|
||||
|
||||
以上是 Astro 组件语法的一个例子,同時包含 HTML 和 JSX。
|
||||
|
||||
你可以在 `src/pages` 目录下创建更多的页面,Astro 将使用该文件名在你的网站上创建新的页面。例如,通过在 `src/pages/about.astro` 创建一个新的文件(重复使用以前的片段),Astro 将生成一个新的页面,URL 为:`http://localhost/about` 。
|
||||
|
||||
## [启动 Astro](#start-astro)
|
||||
|
||||
```bash
|
||||
npm start
|
||||
```
|
||||
|
||||
Astro 会开启预览服务器,地址为 [http://localhost:3000](http://localhost:3000),
|
||||
在浏览器打开这个网址,就会看到 Astro 的 HelloWorld 页面
|
||||
|
||||
服务器会实时监听 'src/' 目录下的文件改动,所以在开发过程的支持热更新,修改程序后,无需重启。
|
||||
|
||||
## [Build Astro](#build-astro)
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
这将让 Astro 打包你的网站并直接保存到磁盘。你的应用程序现在已经在 `dist/` 目录中打包好了。
|
||||
|
||||
## 下一步
|
||||
|
||||
成功了!现在即可开始开发!
|
||||
|
||||
我们建议花点时间用于熟悉 Astro 的运作方式。只要在文档中进一步探索,建议看看这些:
|
||||
|
||||
📚 深入了解 Astro 的项目结构:[项目结构](/core-concepts/project-structure)
|
||||
|
||||
📚 深入了解 Astro 的组件语法:[Astro 组件指南](/core-concepts/astro-components)
|
||||
|
||||
📚 深入了解 Astro 根据文件路径生成路由:[路由指南](core-concepts/astro-pages)
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue