One place for hosting & domains

      Generate

      How To Generate Pages from Markdown in Gatsby


      The author selected the Internet Archive to receive a donation as part of the Write for DOnations program.

      Introduction

      One of the key features of the popular static site generator Gatsby is its flexibility in consuming content sources. Gatsby can generate static pages from almost any data source, such as a Content Management System (CMS), API, database, or even a local file system.

      Markdown files are a popular file-based source to use with Gatsby. Markdown is a markup language that is lightweight and designed for readability, which makes it ideal for documentation projects, blog posts, or any text-heavy websites.

      In this tutorial, you will create a Gatsby-powered static site that builds itself from local Markdown source files, using the gatsby-source-filesystem plugin to collect the files and the gatsby-transformer-remark plugin to convert them into HTML.

      Prerequisites

      Before starting, here are a few things you will need:

      • A local installation of Node.js for running Gatsby and building your site. The installation procedure varies by operating system, but DigitalOcean has guides for Ubuntu 20.04 and macOS, and you can always find the latest release on the official Node.js download page.
      • Some familiarity with JavaScript, for working in Gatsby. The JavaScript language is an expansive topic, but a good starting spot is our How to Code in JavaScript series.
      • Some familiarity with React and JSX, as well as HTML elements, if you want to customize the user interface (UI) of your posts beyond what is covered in this tutorial.
      • A new Gatsby project named markdown-tutorial, scaffolded from gatsby-starter-default. To build a new Gatsby project from scratch, you can refer to Step 1 of the How To Set Up Your First Gatsby Website tutorial.

      This tutorial was tested on Node.js v14.16.1, npm v6.14.12, Gatsby v3.10.2, gatsby-source-filesystem v3.10.0, and gatsby-transformer-remark v4.7.0.

      Step 1 — Standardizing Your Markdown Content

      Given Markdown’s flexibility as a markup language, documents written in Markdown can take on various forms and levels of complexity. Gatsby does not require you to format all your Markdown files in the same way, but to make your site and URLs easier to organize, you will first standardize how you write and store your Markdown files within this project.

      For this tutorial, you will add blog posts to your site, and each post will have a title, customized URL, publication date, and post body. You will start with a single post, Learning About Gatsby, where you can share your experience of learning about Gatsby with the world.

      In preparation for storing this and future posts, create a new directory under src, named blog. If you prefer to do this from the command line, you can do so with mkdir from the root directory of the project:

      Next, create an empty Markdown file within that new directory. For the purposes of this tutorial, filenames do not control the published URL or SEO, so the naming conventions here are just to keep things organized. Give your new post a filename of learning-about-gatsby.md.

      You can either do this in your IDE, or use the terminal with touch:

      • touch src/blog/learning-about-gatsby.md

      Finally, fill in the actual content of the post. Open the file in your editor of choice and add the following:

      markdown-tutorial/src/blog/learning-about-gatsby.md

      ---
      title: "Learning about Gatsby"
      slug: "/blog/learning-about-gatsby"
      date: "2021-08-01"
      ---
      
      ## What I'm Working On
      
      Right now, I'm working through a [DigitalOcean tutorial](https://www.digitalocean.com/community/tutorials) on using [Gatsby](https://www.gatsbyjs.com/) with Markdown.
      

      The top section enclosed by --- is called frontmatter and consists of key-value pairs. It is written in YAML, which is a configuration language outside of Markdown. Property keys go on the left, and your values go on the right. In your frontmatter block, you have defined values for your post’s title, the publication date, and the slug. The slug is the customized portion of the post’s URL that comes after your domain name (also known as the path).

      Any text below the frontmatter will become the post body. Within that area, you have a heading of What I'm Working On, with two hash symbols (##) at the beginning of the line. In Markdown, this indicates a level-2 heading, which Gatsby will convert into <h2></h2> in HTML. Within the text below that heading, you have some links that are written using Markdown syntax: [link_text](link_destination).

      Save your changes to learning-about-gatsby.md and then close the file.

      You have just created your first post using Markdown and saved it within your project’s source code. You have also standardized the format, including specific property values in the frontmatter of the blog posts. This keeps your source code organized and will be important for later steps. For now, the next step is to install and configure the plugins that are required for Gatsby to process this new Markdown post.

      Step 2 — Installing and Configuring the Required Plugins

      With your Markdown file in place, it is time to tell Gatsby where to find them and process them. In this step, you will install the plugins that are required to achieve this and update the Gatsby configuration to load them.

      Two plugins are required to process Markdown in Gatsby: gatsby-transformer-remark and gatsby-source-filesystem. gatsby-transformer-remark will parse your Markdown and convert your frontmatter into fields that Gatsby can query, and gatsby-source-filesystem will allow you to bring data from your local filesystem into your application.

      Install both at the same time by running the following command in your Gatsby project directory:

      • npm install gatsby-source-filesystem gatsby-transformer-remark

      After you install both plugins, open up the main Gatsby configuration file that lives in the root of your project folder: gatsby-config.js. By editing this file, you are telling Gatsby how to use the newly installed plugins to read your Markdown files and begin processing them. Add the following code to your config file:

      markdown-tutorial/gatsby-config.js

      module.exports = {
      ...
        plugins: [
          `gatsby-plugin-react-helmet`,
          `gatsby-plugin-image`,
          {
            resolve: `gatsby-source-filesystem`,
            options: {
              name: `images`,
              path: `${__dirname}/src/images`,
            },
          },
          {
            resolve: `gatsby-source-filesystem`,
            options: {
              name: `blog`,
              path: `${__dirname}/src/blog`,
            },
          },
          `gatsby-transformer-remark`,
          `gatsby-transformer-sharp`,
      ...
      

      The first block loads the gatsby-source-filesystem plugin and passes it an options object telling it to scan the src/blog directory for files and use the blog name as a label for the collection. The final line loads the gatsby-transformer-remark plugin with all default options, since you don’t need to customize them for this tutorial.

      You have now configured Gatsby to load the two plugins that are necessary for scanning in and parsing your Markdown files. In the next step, you will create a page template file for Gatsby to combine with your Markdown content and render as web pages.

      Step 3 — Creating a Page Template File

      Gatsby will now scan your Markdown files and process them with gatsby-transformer-remark, but it still needs instructions on how to display them in the browser. This step covers how to give it those instructions by adding a page template file (also known as a page template component).

      First, create an empty file in src/pages with a filename of {MarkdownRemark.frontmatter__slug}.js. The filename needs to exactly match this, because it uses a Gatsby API called the File System Route API, in which filenames dictate the routes (URLs) created on your site.

      Note: The File System Route API is a newer feature in Gatsby, and you might still see other Markdown page tutorials that involve the createPages API in gatsby-node.js instead. Although it is not deprecated, that API is no longer necessary for the use case covered by this tutorial. However, if you have a project that involves creating arbitrary pages that don’t mirror the file system or exceeds the capabilities of the File System Route API in some other way, you might still need to use the createPages approach.

      To create your component, add the following code to the file:

      markdown-tutorial/src/pages/{MarkdownRemark.frontmatter__slug}.js

      import { graphql } from "gatsby";
      import * as React from "react";
      import Layout from "../components/layout";
      import Seo from "../components/seo";
      
      export default function BlogPostTemplate({ data: { markdownRemark } }) {
        const { frontmatter, html } = markdownRemark;
        return (
          <Layout>
            <Seo title={frontmatter.title} />
            <h1>{frontmatter.title}</h1>
            <h2>{frontmatter.date}</h2>
            <div className="post-body" dangerouslySetInnerHTML={{ __html: html }} />
          </Layout>
        );
      }
      
      export const pageQuery = graphql`
        query ($id: String!) {
          markdownRemark(id: { eq: $id }) {
            html
            frontmatter {
              date(formatString: "MMMM DD, YYYY")
              title
            }
          }
        }
      `;
      

      This code has two main sections. The one at the end of the file is pageQuery, which uses the Gatsby GraphQL tag to evaluate the GraphQL query that follows it. The results of that query are passed to the BlogPostTemplate function and give you access to properties of the post fetched over GraphQL.

      The BlogPostTemplate function is a React component that returns JSX. Within the BlogPostTemplate you display the values of each post’s standardized frontmatter fields, the title and the date, in header elements. The actual body of the post you have placed into a <div> with a class of post-body, using React’s dangerouslySetInnerHTML property to directly echo out the HTML into the rendered result.

      Finally, using export default before declaring the BlogPostTemplate function is necessary in your code, because Gatsby will expect the default export of each page template file to be the React component responsible for producing the final rendered page.

      Now that you have added the template code to the file, save the changes and close it.

      In completing this step, you added a brand new page template file to your Gatsby project. With a filename that uses the File System Route API, it dynamically creates routes and pages based on GraphQL results and your Markdown source files. This was the final step to get Gatsby to generate pages from Markdown. In the next step, you will see these pages in action, as well as add new ones.

      With all the code now in place to turn your Markdown blog posts into web pages, you can now preview your work and add more Markdown content to your site.

      To preview your new blog posts and all the work you have done so far, run this command in your project directory:

      Once Gatsby is ready, it will prompt you to open your project in your web browser, which you can do by navigating to localhost:8000. However, this will first only show you the homepage of your Gatsby application instead of the blog post. To see your new Markdown blog post, navigate to localhost:8000/blog/learning-about-gatsby/. You will find your Markdown file rendered as HTML:

      Blog post titled

      From now on, you can continue to add new blog posts by creating Markdown files in the src/blog directory. Each time you create a new post, remember to follow the conventions you set up for your frontmatter. This means making sure to start the slug value with /blog/ followed by the custom path you want, as well as providing the post with a title and date.

      To test this out, copy your learning-about-gatsby.md Markdown file to be the base of a new post named continuing-learning.md:

      • cp src/blog/learning-about-gatsby.md src/blog/continuing-learning.md

      Next, open the new file and make the following highlighted changes to the content:

      markdown-tutorial/src/blog/continuing-learning.md

      --- 
      title: "Continuing to Learn"
      slug: "/blog/continuing-learning"
      date: "2021-08-01" 
      --- 
      
      ## Update
      
      I'm continuing to learn Gatsby to build some fast static sites!
      

      In this file, you kept the formatting the same but changed the title and slug of the frontmatter and the content of the blog post. Save the file then exit from it.

      Once your server has rebuilt your Gatsby site, navigate to http://localhost:8000/blog/continuing-learning in your browser. You will find the new post rendered at this URL:

      Blog post titled

      Note: If you wanted to add Markdown pages outside of blog, you could do so by modifying the slug to whatever path you would like. If you do this, make sure to use folders to keep your files organized.

      You now have new pages generated from Markdown in Gatsby and have previewed the results.

      Conclusion

      By following the steps in this tutorial, you added Markdown content to your Gatsby project, configured Gatsby to find the files and process them, and created template code to render each post as a new page. Although some of these steps could be omitted by using a Markdown-specific Gatsby Starter template, going through the process manually allows you to customize your Markdown-powered Gatsby site exactly how you want it.

      Although you can link to any new post or page using the Gatsby Link component, if your site has a large amount of Markdown files that are rapidly changing you might want to explore adding a dynamic listing as a next step, so visitors to your site can quickly find all your most recent posts and navigate to each one. To do so, you could use a Gatsby GraphQL tag to query the Markdown posts you want to list, and then iterate over them and display them as links. You can read more about this in this Adding a List of Markdown Blog Posts tutorial.

      If you would like to read more on Gatsby, check out the rest of the How To Create Static Web Sites with Gatsby.js series.



      Source link

      All the Ways to Generate a Next.js Site


      How to Join

      This Tech Talk is free and open to everyone. Register on Eventbrite here to receive a link to join on Wednesday, January 27, 2021, 11:30 a.m.–12:30 p.m. ET.

      About the Talk

      Next.js is an amazing tool that lets us build sites quickly. It handles things like routing, lazy loading, and image optimization. Learn how Next.js allows us to build the fastest possible site.

      What You’ll Learn

      • How Next.js features help us build the fastest possible blogs, websites, and applications
      • Using Incremental Static Generation to update static content after you have built your site
      • Grabbing data from an API

      This Talk is Designed For

      React developers that are looking to streamline your workflow.

      About the Presenter

      Chris Sev is a Senior Developer Advocate at DigitalOcean and the founder of scotch.io. He builds fullstack apps with JavaScript and puts a focus on building businesses.

      To join the live Tech Talk, register here.



      Source link

      How To Generate a Vue.js Single Page App With the Vue CLI


      The author selected Open Sourcing Mental Illness to receive a donation as part of the Write for DOnations program.

      Introduction

      Vue.js is a popular JavaScript framework for creating user interfaces. Created in 2014 by Evan You (formally of Google), Vue.js is often described as a combination of React and Angular, borrowing the prop-driven development of React and the templating power of Angular. This makes Vue an accessible framework for beginners to pick up, especially since it focuses on traditional HTML and CSS, rather than being a CSS-in-JS framework like React or relying on TypeScript (a superset of JavaScript) like Angular does.

      When starting a new project, it’s best to familiarize yourself with the technology’s tools and features. One important tool for Vue.js development is its command line interface (CLI) known as Vue CLI 3. The Vue CLI offers a number of useful features that enhance the Vue development experience, but the main feature is its ability to generate and pre-configure a new single-page application with the vue create command.

      By the end of this tutorial, you will have a working Vue.js application running on a local Node server. This local server uses hot module reloading via Webpack to provide immediate feedback, rendered in-browser as you work. Along the way, you will create .vue single-file components (SFC), such as a header and a footer. All of this you can save as a solid foundation for any future Vue projects.

      Prerequisites

      To follow this tutorial, you will need the following:

      Step 1 — Downloading Vue CLI 3

      To download Vue CLI 3, you will need to run a command either via npm or Yarn, whichever you prefer. npm or Node Package Manager is a way to download and manage other people’s code to use in your project as a dependency. Yarn, on the other hand, executes NPM commands under the hood but provides additional features like caching. It’s up to personal preference regarding which one to use. However, it is important to note that it’s not recommended to mix commands. It’s best to be consistent with one or the other for the duration of your project.

      Moving forward, this tutorial will use npm commands. The following command will download the necessary Vue CLI files from the registrar, which in this case is the npm (Node Package Manager) service:

      npm i -g @vue/cli
      

      Note: On some systems, installing an npm package globally can result in a permission error, which will interrupt the installation. Since it is a security best practice to avoid using sudo with npm install, you can instead resolve this by changing npm’s default directory. If you encounter an EACCES error, follow the instructions at the official npm documentation.

      You install this globally in order to use the CLI anywhere on your machine. If you don’t install this globally, it will only work in the directory that you installed it at. In the case of the command options, i means “install” and -g is a flag to install the code globally on your computer.

      To verify if Vue CLI 3 was properly installed, run the following:

      vue --version
      

      You will receive the following output with a version number. Your version number may differ, but if you receive a response with a version number, you’ve properly installed Vue CLI 3:

      Output

      @vue/cli 4.5.6

      To update Vue CLI 3, run the previous commands in this section, and the latest version will be installed.

      At this point, you have successfully downloaded npm globally along with the Vue CLI tool that you will use in the next section to create a generated Vue.js project.

      Step 2 — Generating a Single-Page Application

      As you develop Vue.js applications, you may find that manually configuring a project is not the most productive use of your time, since configuring a new Vue.js project from scratch can take hours. This is the true power of Vue CLI: It provides you with a pre-generated template that is based on your specifications. Because of this, it’s already configured so you can start developing your website or application right away. Vue CLI 3 will ask you a few questions via a command line prompt about your project, download the required files, and pre-configure it for you so you are ready to work as soon as it’s done.

      To generate a single-page application, navigate to the directory you’d like your Vue project in, then run the following:

      vue create vue-starter-project
      

      The highlighted section of the command is the name of the root directory of the project. This will be the name of the folder that contains all of your Vue.js project files. This can be whatever you’d like, but in the case of this tutorial, you will use vue-starter-project.

      Once you type out that command, continue by pressing Enter. You will then receive the following prompt:

      Vue CLI v4.5.6
      ? Please pick a preset: 
        Default ([Vue 2] babel, eslint) 
        Default (Vue 3 Preview) ([Vue 3] babel, eslint) 
      ❯ Manually select features 
      

      If you do not want to configure your project and opt for the defaults, you can do so with either Vue 2 or Vue 3. For the purpose of this tutorial though, it’s recommended to manually select your features. By selecting specific features, you will see how each option you selected was installed by the CLI.

      Select Manually select features with ENTER. Immediately you’ll receive a number of different options, including: Choose Vue version, TypeScript, Router, and Vuex. Notice that some of these items are already selected (the bubble is filled in). You may select as many or as few as you’d like. However, for this tutorial, select the following by pressing <space> on the entry:

      ...
       ◉ Choose Vue version
       ◉ Babel
       ◉ TypeScript
       ◯ Progressive Web App (PWA) Support
       ◉ Router
       ◉ Vuex
       ◉ CSS Pre-processors
       ◉ Linter / Formatter
      ❯◯ Unit Testing
       ◯ E2E Testing
      

      Once you have your options selected, press the ENTER key. The CLI will ask you further questions regarding each of the features you selected for your project, in order. The first question will ask which version of Vue you’d like to use: 2.x or 3.x. You’ll use Vue 3 for this tutorial, but you may want to use Vue 2 if you want greater support from the Vue Community:

      ...
      ? Choose a version of Vue.js that you want to start the project with 
        2.x 
      ❯ 3.x (Preview)
      

      The next question is regarding TypeScript integration. If you are not familiar with TypeScript, that’s alright. This option was intentionally selected to illustrate how Vue CLI 3 downloads what you defined as required for unique project. This tutorial will not use the class-style syntax, but will use Babel alongside TypeScript.

      When encountering the following, enter N:

      ...
      Use class-style component syntax? (y/N) N
      

      In the following prompt, enter Y:

      ...
      ? Use Babel alongside TypeScript (required for modern mode, auto-detected polyfills, transpiling JSX)? (Y/n) Y
      

      Next, Vue CLI will ask about history mode. History mode will make each route its own URL. This means you will not have the /#/ (hash) in your application’s URL. If you do use history mode, you will need a Node server to run your project. This is not a problem, because Vue CLI 3 provides you with a Node server.

      Type Y to answer yes to history mode:

      ...
      ? Use history mode for router? (Requires proper server setup for index fallback in production) (Y/n) Y
      

      The next question is regarding CSS pre-processors such as Sass or LESS. A CSS pre-processor is CSS with added features like nesting and variables. The browser cannot read this, so when the project is built, Node will compile all of your SCSS or LESS code to traditional CSS. Since you are using Node to build your project, it’s recommended to select Sass/SCSS (with node-sass) as your pre-processor. Later on, you’ll add lang attributes in your .vue components to enable SCSS on a per component basis:

      ...
      ? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): 
        Sass/SCSS (with dart-sass) 
      ❯ Sass/SCSS (with node-sass) 
        Less 
        Stylus 
      

      After that, you will receive some questions regarding the linter style. A linter is a program that evaluates your code as you develop your application. This linter can enforce a number of syntactical rules during development. In addition to this, your integrated development environment (IDE) can read this configuration file and format your code on save. This will keep your code consistent no matter who works on your project and what operating system or IDE a developer is using.

      For this tutorial, choose ESLint + Standard config:

      ...
      ? Pick a linter / formatter config: 
        ESLint with error prevention only 
        ESLint + Airbnb config 
      ❯ ESLint + Standard config 
        ESLint + Prettier 
        TSLint (deprecated) 
      

      This selects a set of rules for ESLint to enforce. These configurations include options like the use of trailing commas, semi-colons at the end of a line, or using const over var in JavaScript.

      The next option is selecting when you want ESLint to format your code. This can be either on save or when you commit your code to a service like GitHub, GitLab, or BitBucket. It’s recommended to select Lint on save so you can review any changes before committing to version control:

      ...
      ? Pick additional lint features: (Press <space> to select, <a> to toggle all, <i> to invert selection)
      ❯◉ Lint on save
       ◯ Lint and fix on commit
      

      Once you select your lint features, Vue CLI will ask you about how you want to store these configurations, whether in dedicated files or in the package.json. It’s considered standard practive to store configurations in their own files for a few reasons. One, configurations are easier to share between projects this way, and two, you’ll be keeping your package.json as legible as possible by only defining the important information about your app:

      ...
      ? Where do you prefer placing config for Babel, ESLint, etc.? (Use arrow keys)
      ❯ In dedicated config files 
        In package.json
      

      Once you are done, the CLI tool will ask if you want to save this selection as a preset for future projects. This is useful if you are generating projects for your employer and you want everything to stay consistent.

      Go ahead and save this configuraion as a preset; Vue CLI will ask you to rename it. Name it DigitalOcean Vue Tutorial Series:

      ...
      ? Save this as a preset for future projects? Yes
      ? Save preset as: DigitalOcean Vue Tutorial Series
      

      Now you can use these exact same settings for a future project.

      At this point, you will have something along the lines of this in your terminal summarizing all of your options:

      ? Please pick a preset: Manually select features
      ? Check the features needed for your project: Choose Vue version, Babel, TS, Router, Vuex, CSS Pre-processors, Linter
      ? Choose a version of Vue.js that you want to start the project with 3.x (Preview)
      ? Use class-style component syntax? No
      ? Use Babel alongside TypeScript (required for modern mode, auto-detected polyfills, transpiling JSX)? Yes
      ? Use history mode for router? (Requires proper server setup for index fallback in production) Yes
      ? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Sass/SCSS (with node-sass)
      ? Pick a linter / formatter config: Standard
      ? Pick additional lint features: Lint on save
      ? Where do you prefer placing config for Babel, ESLint, etc.? In dedicated config files
      ? Save this as a preset for future projects? (y/N) 
      

      Press ENTER, and Vue CLI will start creating your app.

      When completed, cd (change directory) in your project name (vue-starter-project):

      Next, start the application with npm run serve. This will run your project at a port on your localhost, usually :8080. If it’s a different port, the CLI will tell you:

      npm run serve
      

      You do not need to download dependencies, as the CLI already did that for you. To view your generated project, open your browser of choice and visit localhost:8080 in the URL bar. You will find a welcome screen with the Vue logo and the technologies you’ve selected in the previous steps.

      Vue template screen

      You can leave this server running throughout this tutorial to monitor your changes.

      In this section, you selected a number of options specific to the project you are creating. Vue CLI downloaded all of the code needed and pre-configured it for you. You can now start working in the generated code base, including creating your own single-file .vue components.

      Now that you have a single-page application running on a Node server, make some changes to this by creating a standard header and footer. These AppHeader.vue and AppFooter.vue components will be imported in such a way that they’ll be present on each route.

      In a new terminal window, navigate into the root of your vue-starter-project folder and list out the files with the following command:

      You will receive the following output:

      Output

      README.md babel.config.js node_modules package-lock.json package.json public src tsconfig.json

      You can also view the contents of your project by opening your project in your editor of choice, such as Visual Studio Code. In either case, you will have access to a number of different files and directories. These config files in the root directory have been created because of the selections made during the intial generation of this project. The option In dedicated config files told Vue CLI to create config.js files for each service you are using, such as Babel, TypeScript, and ESLint. In addition to these files, there are a number of directories. This tutorial will go over these as you get to them.

      First, create a .vue file in the components directory and name it AppHeader.vue. You can do this right-clicking in the components directory and creating a new file in IDEs like VS Code. If you prefer terminal commands, you can do this in your computer’s terminal with the bash command touch:

      touch src/components/AppHeader.vue
      

      In this step, you are creating a single-file component that will contain all of the HTML, JavaScript, and SCSS that this chunk of code needs. Every .vue component contains three basic concerns or sections: <template>, <script>, and <style>. In this case, template is the component’s HTML.

      Open up the new file in your text editor.

      In this file, create a header by using the <header> tag inside of <template>. Inside of this <header>, add the Vue.js logo and a <p> element with the content My Vue.js Application:

      vue-starter-project/src/components/AppHeader.vue

      <template>
        <header>
          <img alt="Vue logo" src="https://www.digitalocean.com/community/tutorials/assets/logo.png" height="50">
          <p>My Vue.js Application</p>
        </header>
      </template>
      

      Keep your development server running throughout development. If you close or cancel the server process, you will not be able to view your application in the browser.

      Save the file.

      At this point, when you open your browser, you will not see the HTML rendered. That is because you need to import the newly created AppHeader.vue component into a component that is already mounted. Since App.vue is your main entry point, it’s best to import it there so our header appears on every route.

      Open up the App.vue file in your text editor, then delete the div with the ID of nav and add the following highlighted code:

      vue-starter-project/src/App.vue

      <template>
        <app-header />
        <router-view/>
      </template>
      
      <script>
      import AppHeader from '@/components/AppHeader.vue'
      
      export default {
        components: {
          AppHeader
        }
      }
      </script>
      

      When you import using ES6, you are essentially creating a variable to later reference in your code. In this case, you are storing the code from AppHeader.vue into a variable called AppHeader. You need to register it via the components property before you can use it.

      Once it’s imported, you deleted the #nav in the template and added <app-header /> before the <router-view />. This renders the component in the HTML.

      After completing this step, save any unsaved file and open your browser back to localhost:8080. Thanks to hot module reloading, you will now find your newly created header at the top of the page:

      Vue template with new header

      You’ve now created a single-file Vue component, used import to bring it into a mounted component, and monitored the change with hot module reloading (HMR). Moving forward, you will extend the functionality of components through the use of child components. You will also use SCSS (the pre-processor you selected earlier) on a per component basis with the lang attribute.

      Now that the header is imported properly into the application, return to AppHeader.vue in your text editor. Add navigation underneath <p>My Vue.js Application</p> by adding the following highlighted code:

      vue-starter-project/src/components/AppHeader.vue

      <template>
        <header>
          <img alt="Vue logo" src="https://www.digitalocean.com/community/tutorials/assets/logo.png" height="50">
          <p>My Vue.js Application</p>
          <nav>
            <ul>
              <li><router-link to="/">Home</router-link></li>
              <li><router-link to="/about">About</router-link></li>
            </ul>
          </nav>
        </header>
      </template>
      

      Now, style this to make it look more like a traditional navigation bar. Create a <style> tag at the end of the file.

      vue-starter-project/src/components/AppHeader.vue

      <template>
        <header>
          <img alt="Vue logo" src="https://www.digitalocean.com/community/tutorials/assets/logo.png" height="50">
          <p>My Vue.js Application</p>
          <nav>
            <ul>
              <li><router-link to="/">Home</router-link></li>
              <li><router-link to="/about">About</router-link></li>
            </ul>
          </nav>
        </header>
      </template>
      
      <style lang="scss">
      </style>
      

      During the inital setup, you selected the Sass/SCSS (with node-sass) option. This is why you added on the lang="scss" attribute to your style tag. If you are unfamiliar with SCSS, it’s recommended to view their official documentation for specifics on when to use nesting or variables.

      This lang attribute will give you the ability to write SCSS in your single-file component. Add the following highlighted contents in the style element:

      vue-starter-project/src/components/AppHeader.vue

      ...
      <style lang="scss">
        header {
          display: flex;
          border-bottom: 1px solid #ccc;
          padding: .5rem 1rem;
      
          p {
            margin-left: 1rem;
          }
        }
      
        nav {
          margin-left: auto;
      
          ul {
            list-style: none;
          }
      
          ul li {
            display: inline-flex;
            margin-left: 1rem;
          }
        }
      </style>
      

      This SCSS creates a horizontal navigation bar with declarations such as display: inline-flex (using Flexbox) and spaces each item out with margin-left auto. To separate the header from the rest of the content, some padding is applied with padding: .5rem 1rem along with a bottom border using border-bottom: 1px solid #ccc. You may notice that the p styles are inside of the header SCSS block. In traditional CSS, that is not allowed, but thanks for SCSS, you can do that. This is refered to as nesting. In this case, the p inside the header is the same as selecting header p in traditional CSS.

      Save your file and navigate to localhost:8080 in your browser to find the new style:

      New style for header in Vue template

      You now have created and styled your header component. Next, you will create the footer component.

      Now that you have a header, you will complete your example application with a footer. In the same components directory, create a new file with the name AppFooter.vue. The process of creating this component is the same as creating the AppHeader.vue. You can create the file in your editor or through the touch base command.

      touch src/components/AppFooter.vue
      

      As before, import this into your App.vue file. Open up App.vue and add the following highlighted code:

      vue-starter-project/src/App.vue

      <template>
        <app-header />
        <router-view/>
        <app-footer />
      </template>
      
      <script>
      import AppHeader from '@/components/AppHeader.vue'
      import AppFooter from '@/components/AppFooter.vue'
      
      export default {
        components: {
          AppHeader,
          AppFooter
        }
      }
      </script>
      ...
      

      This time, you’re importing the component after the router-view tag.

      Save the file, then open up AppFooter.vue. In your AppFooter.vue file, use the <footer> HTML tag with a paragraph:

      vue-starter-project/src/components/AppFooter.vue

      <template>
        <footer>
          <p>Copyright &copy; "current year" </p>
        </footer>
      </template>
      

      You now have a basic footer. Continue to expand on this to include the current year programmatically. This will be dynamic depending on what the year is. To achieve this, you will create a computed property. A computed property is a reactive value calculated with JavaScript.

      In Vue 3, you need to wrap your properties in the setup() function and return these values. Essentially, you are telling Vue to construct this component and provide the template to these reactive computed properties.

      To create a computed property, you’ll first need to deconstruct the computed function from the vue library. You will store this computed function and its value into a const. In Vue 3, you need to pass an anonymous function that returns a value:

      const year = computed(() => new Date().getFullYear())
      

      To add the setup function to your file, add the following script to the end of AppFooter.vue:

      vue-starter-project/src/components/AppFooter.vue

      ...
      <script>
      import { computed } from 'vue'
      
      export default {
        setup () {
          const year = computed(() => new Date().getFullYear())
        }
      }
      </script>
      

      After that, you will need to provide access to the computed property you created for the <template> to consume and render. Return an object with the year property and value in your setup() function:

      /vue-starter-project/src/components/AppFooter.vue

      ...
      setup () {
        const year = computed(() => new Date().getFullYear())
        return { year }
      }
      ...
      

      To use this value in the <template>, use interpolation with double curly braces. This is sometimes referred to the “moustache syntax”:

      /vue-starter-project/src/components/AppFooter.vue

      <template>
        <footer>
          <p>Copyright &copy; {{ year }}</p>
        </footer>
      </template>
      

      Save the file. You will now have the current year in your footer:

      Sample vue application with a computed header

      Conclusion

      In this tutorial, you downloaded the Vue CLI and created your own single-file components with AppHeader.vue and AppFooter.vue. You successfully generated a Vue.js Single Page Application (SPA) with selected features from the initial setup, and learned how all of those pieces come together. In addition, you’ve now reviewed the basic architecture of most SPAs and can use that knowledge to futher expand this project.

      Vue.js is a growing ecosystem with a number of tools at your disposable. These tools can help you quickly get started and save time by storing options as a preset. This is just the start of what Vue.js has to offer, but the CLI is perhaps one of the most important tools you will use in your Vue.js journey.

      For more information on Vue.js and Vue CLI 3, it’s recommended to read through their documentation. The CLI tool specifically has many additional features that weren’t covered in this tutorial. For more tutorials on Vue, check out the Vue Topic Page.



      Source link