21

Astro JS Tutorial: Quick Start Astro Guide | Rodney Lab

 2 years ago
source link: https://rodneylab.com/astro-js-tutorial/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
NEXT POST >
LATEST POST >>

Astro JS Tutorial: Quick Start Astro Guide #

Updated an hour ago
10 minute read Gunning Fog Index: 6.5
Content by Rodney
SHARE:

🧑🏽‍🎓 Astro JS Tutorial #

In this Astro JS tutorial, we will see how create an AstroJS site from spinning up a local development server right up to getting the app into the cloud and hosting. Although we will build a fairly simple site, we will see some important Astro features like hydration in action. We will also take advantage of Astro’s Islands architecture to add Svelte and React components. This is just a quick introduction to Astro so be sure to explore the related posts and videos listed at the bottom of the page to boldly go further!

🧱 Astro JS Tutorial: What we’re Building #

Astro JS Tutorial: Quick Start Astro Guide: Building

We build a simple app which shows YouTube videos in Svelte and React as well as an Astro Markdown component. We will do that in three steps. First of all is the setup, which should take a couple of minutes. Then we will add our own content to the minimal app we created in the previous step. Finally, we will see how to deploy the app to the cloud.

🧑🏽‍🦼 Quick Start #

Astro JS Tutorial: Quick Start Astro Guide

You spin up a new Astro project from the command line. First you need to create a new directory for the project, then change into that directory and spin up Astro. We will be using Svelte and React in our Astro JS tutorial app. We can configure Astro to use these as part of the setup. Let’s do that now, running these commands:

To get going straight away, clone the repo then fire up a dev server with these few lines in the Terminal:

mkdir astro-js-tutorial && cd $_
pnpm init astro
pnpm install
pnpm astro add react svelte
pnpm run dev

In the init astro step, select Minimal. Then in the astro add step enter yes so Astro configures React and Svelte for you. After the final step you should have a dev server running. The Terminal will give you the URL for it so you can open it in your browser. Typically it will be running on http://localhost:3000/ . However, Astro will automatically find a free port if there is already something running on port 3000.

Astro JS Tutorial: Terminal Screenshot > @example/minimal@0.0.1 dev > astro dev 🚀  astro  v1.0.0-beta.7 started in 45ms ┃ Local    http://localhost:3001/ ┃ Network  use --host to expose ▶ This is a  beta  prerelease build Feedback? https://astro.build/issues

Astro JS Tutorial: Quick Start Astro Guide: Terminal

Open up the browser using the given URL and you should just see the word ‘Astro’ in black text. We will add our own content to this minimal app next.

Astro JS Tutorial: Minimal Astro app browser screenshot, contains the word 'Astro' in black text and nothing else

Astro JS Tutorial: Quick Start Astro Guide: Terminal

astro.config.mjs #

Just before moving on open up astro.config.mjs in the project root folder. This is Astro’s main config file. You will see the setup tool has imported the necessary Svelte and React integration packages and added them to the config for you.

🖋 Content #

In this section we are going to build out our app, and learn a little about the structure of an Astro project in the process. We will also see how to add vanilla CSS styling in Svelte.

Astro routing works similar to NextJS, Remix and SvelteKit. Astro generates pages from files in src/routes. So the file you saw in the browser is generated from the content in src/routes/index.astro. Let’s look at that file next.

src/routes/index.astro #

Replace the content in the file with this:

src/routes/index.astro
astro
2 import "$styles/styles.css";
3 import { Markdown } from "astro/components";
4 import ReactVideo from "$components/Video.jsx";
5 import SvelteVideo from "$components/Video.svelte";
8 <html lang="en-GB">
9 <head>
10 <meta charset="utf-8" />
11 <link rel="icon" href="/favicon.png" />
12 <meta name="viewport" content="width=device-width" />
14 <title>RodneyLab Minimal Astro Example</title>
15 </head>
16 <body>
17 <main class="container">
18 <h1>Astro JS Tutorial Site</h1>
19 <p>
20 This demo is not endorsed by Ben Awad, just thought the video content
21 was fitting!
22 </p>
23 <ReactVideo client:load />
24 <SvelteVideo client:load />
25 <section class="mdx-container">
26 <Markdown>
27 ## Astro in 100 Seconds
29 <div class="video-container">
30 <iframe
31 title="Astro in 100 Seconds"
32 width="560"
33 height="315"
34 src="https://www.youtube-nocookie.com/embed/dsTXcSeAZq8"
35 frameborder="0"
36 allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
37 allowfullscreen
38 ></iframe>
39 </div>
40 </Markdown>
41 </section>
42 </main>
43 </body>
44 </html>
46 <style>
47 .container {
48 display: flex;
49 flex-direction: column;
50 background: hsl(
51 var(--colour-dark-hue) var(--colour-dark-saturation)
52 var(--colour-dark-luminance)
54 color: hsl(
55 var(--colour-light-text-hue) var(--colour-light-text-saturation)
56 var(--colour-light-text-luminance)
58 padding: var(--spacing-8) var(--spacing-0) var(--spacing-32);
61 .container a {
62 color: hsl(
63 var(--colour-secondary-hue) var(--colour-secondary-saturation)
64 var(--colour-secondary-luminance)
67 .mdx-container {
68 display: flex;
69 flex-direction: column;
70 background: hsl(
71 var(--colour-alternative-hue) var(--colour-alternative-saturation)
72 var(--colour-alternative-luminance)
74 align-items: center;
75 width: 100%;
76 padding: var(--spacing-8) var(--spacing-0) var(--spacing-12);
77 color: hsl(
78 var(--colour-light-text-hue) var(--colour-light-text-saturation)
79 var(--colour-light-text-luminance)
82 </style>

We have a fair bit in here. Broadly the file has three sections. The first is the frontmatter in lines 16. In the first line we import our global stylesheet. We will create that file in a moment. We also add the components which we will use to add video here. This might be new if you are coming from an HTML / JavaScript / CSS background. Though the other two sections might look a little more familiar. In the frontmatter we can write JavaScript which defines any variables we want to use in the following section. In our case, we are just importing element which we will use in the main markup.

The main markup (lines 844) looks a lot like HTML, with a head and body section. As well as regular HTML elements, we use our ReactVideo and SvelteVideo components.

The final section contains styles. The styles in this file will be automatically scoped just to the content of this file. Our app will not work for the moment; we need to add some of the new content we reference in the frontmatter first.

Hydration #

By default Astro does not load JavaScript — it will not hydrate the page. By including the client:load directive in lines 23 & 24, we tell Astro to hydrate our components. Because of this, when we click the buttons in the app, our JavaScript code will change the background colour.

tsconfig.json #

We will put our components in a new src/components directory. You might notice though that the import statement mentions $components. This is just an alias for src/components which we will use for convenience. For the alias to work, we need to update the tsconfig.json file in the project root folder. Let’s do that:

tsconfig.json
2 "compilerOptions": {
3 "moduleResolution": "node",
4 "baseUrl": ".",
5 "paths": {
6 "$components/*": ["src/components/*"],
7 "$styles/*": ["src/styles/*"]

You will notice we also defined $styles. You can add any other aliases that might make sense for the project you are working on. Note we only add these for convenience, they are optional and as an example we could instead have written import '../styles/styles.css'. I prefer the alias, as well as looking neater, on larger projects where you might have to traverse multiple directories to get to your file, the syntax is more manageable.

src/styles/styles.css #

Speaking of styles, lets add our global styles. Astro works with SCSS, Tailwind and other styling frameworks. To keep this project simple, and also because modern CSS is now quite powerful, we stick to vanilla CSS. Create a src/styles folder and inside, add a styles/css file with the following content:

src/styles/styles.css — click to expand code.

In lines 4258 you will notice we have some self-hosted fonts. We will download those to our project shortly. At the bottom of the file you will see we have some style for our react component. We take a different approach for the Svelte component taking advantage of in-built scoped styles, similar to what we have for the index.astro page.

src/components/Video.jsx #

Next we can paste in the React code. Create a src/components folder and then create a Video.jsx file with the following content inside:

src/components/Video.jsx
1 import { useState } from "react";
3 export const ReactExample = function ReactExample() {
4 const [altColours, setAltColours] = useState(false);
6 return (
7 <section
8 className={`react-container${altColours ? " react-container-alt" : ""}`}
9 >
10 <h2>Example React Component</h2>
11 <div className="video-container">
12 <iframe
13 width="560"
14 height="315"
15 src="https://www.youtube-nocookie.com/embed/PJ0QSJpJn2U"
16 title="Should you Stop Using React"
17 frameBorder="0"
18 allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
19 allowFullScreen
20 />
21 </div>
22 <button
23 className={`react-button${altColours ? " react-button-alt" : ""}`}
24 onClick={() => {
25 setAltColours(!altColours);
27 >
28 <span className="screen-reader-text">Toggle colours</span>
29 </button>
30 </section>
34 export default ReactExample;

src/components/Video.svelte #

The final component we need to add is the Svelte one. The app should work again once we have this in place. Create the Video.svelte file in the components folder, with this content:

src/components/Video.svelte
svelte
1 <script>
2 $: altColours = false;
3 </script>
5 <section class={`container${altColours ? " container-alt" : ""}`}>
6 <h2>Svelte Component</h2>
7 <div class="video-container">
8 <iframe
9 title="Trying Svelte for the Third Time"
10 width="560"
11 height="315"
12 src="https://www.youtube-nocookie.com/embed/xgER1OutVvU"
13 frameborder="0"
14 allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
15 allowfullscreen
16 />
17 </div>
18 <button
19 class={`button${altColours ? " button-alt" : ""}`}
20 on:click={() => {
21 altColours = !altColours;
22 }}><span class="screen-reader-text">Toggle colours</span></button
23 >
24 </section>
26 <style>
27 .container {
28 display: flex;
29 flex-direction: column;
30 background: hsl(
31 var(--colour-brand-hue) var(--colour-brand-saturation)
32 var(--colour-brand-luminance)
34 align-items: center;
35 width: 100%;
36 padding: var(--spacing-8) var(--spacing-0);
37 color: hsl(
38 var(--colour-dark-text-hue) var(--colour-dark-text-saturation)
39 var(--colour-dark-text-luminance)
43 .container-alt {
44 background: hsl(
45 var(--colour-secondary-hue) var(--colour-secondary-saturation)
46 var(--colour-secondary-luminance)
49 color: hsl(
50 var(--colour-light-text-hue) var(--colour-light-text-saturation)
51 var(--colour-light-text-luminance)
55 .button {
56 background: hsl(
57 var(--colour-secondary-hue) var(--colour-secondary-saturation)
58 var(--colour-secondary-luminance)
62 .button-alt {
63 background: hsl(
64 var(--colour-brand-hue) var(--colour-brand-saturation)
65 var(--colour-brand-luminance)
68 </style>

Fonts #

We mentioned that we are using self-hosted fonts above. For the hosting to work,we need to include the fonts in our repo so our host can serve them. Download the Roboto Font in Regular, 400 and 700 . Extract the zip and then create a new fonts folder in the project’s public folder. Drop the four unzipped files in that folder. The public folder is for anything which we do not need Astro (or Vite, under the hood) to process. As well as fonts, web manifest files for PWA and favicons fall into this category.

We won’t optimise fonts here, just to get finished a little quicker. There is a nice video which focusses on self-hosted fonts in Astro together with optimisation. If you are interested in optimisation, do take a look. You can save 80% on some fonts files, especially where, for example you only use the 900 weight font in titles.

🗳 Poll #

Astro can generate SSR as well as static sites. Are you interested in trying SSR at some point?
  • yes, already tried it
  • yes, would like to try it,
  • no idea what SSR is,
  • will stick to static Astro sites.
Voting reveals latest results.

🍧 Hosting #

The app should be working just fine now, with a nice Roboto sans serif font and all the colours. Try pressing the buttons below the React and Svelte components to check they work. You should notice the background colour change.

The next step is to build the site locally to check it is all working as expected. Run these commands to build and preview the site (stop the dev server with ctrl + C first):

pnpm run build
pnpm run preview

If all is well, commit the code to a git repo and upload it to your GitHub or GitLab account, so we can host it as a static site. You might notice your site gets built to the dist directory in your project. There is no need to include this in your repo as your host will generate the site there for you.

It is worth adding a .nvmrc file to the project root folder whichever host you are using. This will tell the host know which version of node to use. We will go for the long-term support (LTS) version which is 16 at the time of writing:

.nvmrc
plaintext

Configuration #

Although we have used pnpm in this tutorial to build the site, for maximum compatibility, in the cloud use npm run build as your build command. We just mentioned that Astro outputs projects to the dist directory, so with you host, set the build output directory or publish directory to dist.

Here are screenshots for Netlify  and Cloudflare Pages  which should help you out. Other services will be similar. Select the Astro preset if your host has one, then just check the build command and output / publish directory is dist.

Astro JS Tutorial: Astro JS Tutorial: Netlify hosting screenshot shows build configuration with base directory blank,build command set to 'npm run build' and publish directory set to 'dist'

Astro JS Tutorial: Quick Start Astro Guide: Netlify Hosting

Astro JS Tutorial: Astro JS Tutorial: Cloudflare pages hosting screenshot shows build configuration with Framework preset set to 'Astro', build command set to 'npm run build' and build output directory set to 'dist'

Astro JS Tutorial: Quick Start Astro Guide: Cloudflare Pages Hosting

🙌🏽 Astro JS Tutorial: Wrapping Up #

In this post we have run through the pipeline for building a static Astro site. We have seen:

  • how to spin up a new Astro project with Svelte and React integrations,
  • how you can add global CSS styles, local scoped styles and style React components with plain CSS,
  • configuration for deploying your static Astro site to the cloud.

The Astro JS tutorial code is in the Rodney Lab GitHub repo . You can also try it on Stackblitz .

I hope you found this article useful and am keen to hear how you will the starter on your own projects as well as possible improvements.

🏁 Astro JS Tutorial: Summary #

Where can you host an Astro site? #

Astro should work on on any host able to build static sites with node. We have seen more detailed build instructions for Netlify and Cloudflare Pages, though you should also be able to get a hassle-free build on Render, Vercel and other similar services.

What are Astro import aliases? #

Astro lets you define import aliases which are essentially syntactic sugar. They let you use an absolute alternative path in your import statements. Because this path is absolute rather that the default relative paths, it does not need to be updated if you move your source file from one folder to another. On top, the syntax is cleaner. We have seen how to define your own custom aliases in the tsconfig.json file.

How do you add vanilla CSS styling in Astro? #

We have seen a few different ways to add stying in Astro. We can add a global stylesheet and import this into astro pages with the regular ES Module import syntax. For less complex apps, we can add React component styling here. On top we can add locally scoped styles in a script tag at the bottom of an Astro page. As this is also a Svelte feature we can style Svelte component in this way too. Using these styling methods, Astro is able to optimise out CSS.

🙏🏽 Astro JS Tutorial: Feedback #

Have you found the post useful? Would you prefer to see posts on another topic instead? Get in touch with ideas for new posts. Also if you like my writing style, get in touch if I can write some posts for your company site on a consultancy basis. Read on to find ways to get in touch, further below. If you want to support posts similar to this one and can spare a few dollars, euros or pounds, please consider supporting me through Buy me a Coffee.

Finally, feel free to share the post on your social media accounts for all your followers who will find it useful. As well as leaving a comment below, you can get in touch via @askRodney on Twitter and also askRodney on Telegram . Also, see further ways to get in touch with Rodney Lab. I post regularly on Astro as well as SvelteKit. Also subscribe to the newsletter to keep up-to-date with our latest projects.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK