[Technical Translation] use Nuxt generate static website

This week again translate some technical articles, this is expected to translate three articles as follows:

I translated technical articles are placed in a github repository, if you find it useful, please click on the star collection. Why should I create this git repository? The purpose is to learn and follow-up web development by translating foreign web-related technical articles of new ideas and technologies. git repository Address: https://github.com/yzsunlei/javascript-article-translate

Static websites pop up again now. Kiosks and branding station no longer need to use a content management system like WordPress to dynamically update.

Use static website builder, you can get content from passive CMS, API and other dynamic source and Markdown files and other documents.

Nuxt is based Vue.js excellent static website generator can be easily used to build static websites. Use Nuxt, build dynamic content from static Web sites need to do is create a template, to API and Markdown files from dynamic sources dynamic. Then, in Nuxt configuration file, we define a static route, so that it can be generated as static content files via the same route.

In this article, we will build use Nuxt news sites, and will use https://newsapi.org/the News API as the content. You must first understand Vue.js, before you can use Nuxt create a site, because Nuxt Vue.js framework is based.

First, we registered API key in the News API site. If we want to get the headlines, it's free. We started to build websites using Nuxt CLI. We run it by typing:

npx create-nuxt-app news-website

This will create the initial project file in news-website folder. When you run the wizard, we do not choose for the server-side frameworks anything, nothing is selected as the UI framework, nothing is selected for the testing framework, do not choose generic file Nuxt mode, the final choice of whether to include Axios depending on your situation request library using the lint code organize and prettify code beautification.

Next, we need to install some packages. We need @nuxtjs/dotenvto read the environment variables in the local packages and country-listused to obtain a list of countries on our website library. To install them, we run:

npm i @nuxtjs/dotenv country-list

Now we can start building our site. In default.vue file, we will replace the existing code:

<template>  
  <div>
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
      <nuxt-link class="navbar-brand" to="/">News Website</nuxt-link>
      <button
        class="navbar-toggler"
        type="button"
        data-toggle="collapse"
        data-target="#navbarSupportedContent"
        aria-controls="navbarSupportedContent"
        aria-expanded="false"
        aria-label="Toggle navigation"
      >
        <span class="navbar-toggler-icon"></span>
      </button> <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav mr-auto">
          <li class="nav-item active">
            <nuxt-link class="nav-link" to="/">Home</nuxt-link>
          </li>
          <li class="nav-item dropdown">
            <a
              class="nav-link dropdown-toggle"
              href="#"
              id="navbarDropdown"
              role="button"
              data-toggle="dropdown"
              aria-haspopup="true"
              aria-expanded="false"
            >Headliny by Country</a>
            <div class="dropdown-menu" aria-labelledby="navbarDropdown">
              <nuxt-link
                class="dropdown-item"
                :to="`/headlines/${c.code}`"
                v-for="(c, i) of countries"
                :key="i"
              >{{c.name}}</nuxt-link>
            </div>
          </li>
        </ul>
      </div>
    </nav>
    <nuxt />
  </div>
</template>

<script>
import { requestsMixin } from "~/mixins/requestsMixin";
const { getData } = require("country-list");

export default {
  mixins: [requestsMixin],
  data() {
    return {
      countries: getData()
    };
  }
};
</script>

<style>
.bg-light {
  background-color: lightcoral !important;
}
</style>

This file is used to define the layout of our website. We are here to add a Bootstrap navigation bar. The bar contains links to the home page drop-down list and national lists. These nuxt-link components are links to pages, the pages used to obtain the title country / region when generating static files. Can be obtained from the national part of the country-list package by calling the function. In this section, we'll change the background color of the navigation bar by overriding the default color class. Components of this section will be displayed at the bottom of our content.

scriptgetDatastyle.bg-lightnuxttemplate

Next, we create a mixins folder and create a file named requestsMixin.jsfile of. In which we add:

const APIURL = "https://newsapi.org/v2";  
const axios = require("axios");
export const requestsMixin = {  
  methods: {  
    getHeadlines(country) {  
      return axios.get(  
        `${APIURL}/top-headlines?country=${country}&apiKey=${process.env.VUE_APP_APIKEY}`  
      );  
    }, getEverything(keyword) {  
      return axios.get(  
        `${APIURL}/everything?q=${keyword}&apiKey=${process.env.VUE_APP_APIKEY}`  
      );  
    }  
  }  
};

This file contains the code used to get by country / territory, and keywords as the title from News API.

Then, in the pages folder, we create headlines folder and file in the folder headlines, create _countryCode.vue file. In the file, we add:

<template>  
  <div class="container">  
    <h1 class="text-center">Headlines in {{getCountryName()}}</h1>  
    <div v-if="headlines.length > 0">  
      <div class="card" v-for="(h, i) of headlines" :key="i">  
        <div class="card-body">  
          <h5 class="card-title">{{h.title}}</h5>  
          <p class="card-text">{{h.content}}</p>  
          <button class="btn btn-primary" :href="h.url" target="_blank" variant="primary">Read</button>  
        </div>  
        <img :src="h.urlToImage" class="card-img-bottom" />  
      </div>  
    </div>  
    <div v-else>  
      <h2 class="text-center">No headlines found.</h2>  
    </div>  
  </div>  
</template>

<script>  
import { requestsMixin } from "~/mixins/requestsMixin";  
const { getData } = require("country-list");

export default {  
  mixins: [requestsMixin],  
  data() {  
    return {  
      headlines: [],  
      countries: getData()  
    };  
  },  
  beforeMount() {  
    this.getHeadlinesByCountry();  
  },  
  methods: {  
    async getHeadlinesByCountry() {  
      this.country = this.$route.params.countryCode;  
      const { data } = await this.getHeadlines(this.country);  
      this.headlines = data.articles;  
    }, 

    getCountryName() {  
      const country = this.countries.find(  
        c => c.code == this.$route.params.countryCode  
      );  
      return country ? country.name : "";  
    }  
  }  
};  
</script>

In this document, we accept the route parameters, countryCode then make calls from that location before we included in this component of the this.getHeadlinesfunction, requestsMixin to get the title from News API. The results are then displayed on the Bootstrap card template portion. In the template, we have to get the name of the country by finding the name of the country from the country-list data. If you can not find the title, we will display a message. In general, if you want to create a URL parameter accepts a page, you must create an underlined as the first character and the desired file name of the URL variable parameters. Thus, in this example, _countryCode.vue countryCode we will use this parameter this.$route.params.countryCode.

Next, index.vue the pages folder, replace the existing code is:

<template>  
  <div class="container">  
    <h1 class="text-center">Home</h1>  
    <div class="card" v-for="(h, i) of headlines" :key="i">  
      <div class="card-body">  
        <h5 class="card-title">{{h.title}}</h5>  
        <p class="card-text">{{h.content}}</p>  
        <button class="btn btn-primary" :href="h.url" target="_blank" variant="primary">Read</button>  
      </div>  
      <img :src="h.urlToImage" class="card-img-bottom" />  
    </div>  
  </div>  
</template>  
<script>  
import { requestsMixin } from "~/mixins/requestsMixin";  
const { getData } = require("country-list");

export default {  
  mixins: [requestsMixin],  
  data() {  
    return {  
      headlines: []  
    };  
  },  
  beforeMount() {  
    this.getHeadlinesByCountry();  
  },  
  methods: {  
    async getHeadlinesByCountry() {  
      const { data } = await this.getHeadlines("us");  
      this.headlines = data.articles;  
    }  
  }  
};  
</script>

<style>  
</style>

This allows us to show the US title on the home page. It works with _countryCode.vue page similar to the difference is that we only get US headlines, and does not accept URL parameters to get headlines from different countries / regions based on URL.

Next, we create-env.js create a project file in the root folder and add the following:

const fs = require('fs')  
fs.writeFileSync('./.env', `API_KEY=${process.env.API_KEY}`)

This allows us to deploy Netlify, because we need to create a file based on dynamic .env environment variable input. In addition, we .env manually create the file, and then API_KEY key as a key, News API API key as the value.

The next nuxt.config.js, we will replace the existing code:

require("dotenv").config();  
const { getData } = require("country-list");

export default {  
  mode: "universal",  
  /*  
   ** Headers of the page  
   */  
  head: {  
    title: "News Website",  
    meta: [  
      { charset: "utf-8" },  
      { name: "viewport", content: "width=device-width, initial-scale=1" },  
      {  
        hid: "description",  
        name: "description",  
        content: process.env.npm_package_description || ""  
      }  
    ],  
    link: [  
      { rel: "icon", type: "image/x-icon", href: "/favicon.ico" },  
      {  
        rel: "stylesheet",  
        href:  
         "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"  
      }  
    ],  
    script: [  
      { src: "https://code.jquery.com/jquery-3.3.1.slim.min.js" },  
      {  
        src:  
          "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"  
      },  
      {  
        src:  
          "https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"  
      }  
    ]  
  },  
  /*  
   ** Customize the progress-bar color  
   */  
  loading: { color: "#fff" },  
  /*  
   ** Global CSS  
   */  
  css: [],  
  /*  
   ** Plugins to load before mounting the App  
   */  
  plugins: [],  
  /*  
   ** Nuxt.js dev-modules  
   */  
  buildModules: [],  
  /*  
   ** Nuxt.js modules  
   */  
  modules: [  
    // Doc: https://axios.nuxtjs.org/usage    
    "@nuxtjs/axios",  
    "@nuxtjs/dotenv"  
  ],  
  /*  
   ** Axios module configuration  
   ** See https://axios.nuxtjs.org/options
   */  
  axios: {},  
  /*  
   ** Build configuration  
   */  
  build: {  
    /*  
     ** You can extend webpack config here  
     */  
    extend(config, ctx) {}  
  },  
  env: {  
    apiKey: process.env.API_KEY || ""  
  },  
  router: {  
    routes: [  
      {  
        name: "index",  
        path: "/",  
        component: "pages/index.vue"  
      },  
      {  
        name: "headlines-id",  
        path: "/headlines/:countryCode?",  
        component: "pages/headlines/_countryCode.vue"  
      }  
    ]  
  },  
  generate: {  
    routes() {  
      return getData().map(d => `headlines/${d.code}`);  
    }  
  }  
};

In the head object, we changed the title to display the desired title instead of the default title. In the link, we add the Bootstrap CSS, the script, we add the Bootstrap JavaScript files and jQuery, Bootstrap are dependencies. Because we want to build a static site can not be used BootstrapVue, as it is dynamic. We do not want to use any dynamic JavaScript in the generated output, so we must use common Bootstrap. In the modules, we add "@ nuxtjs / dotenv" the ability to read environment variables created from .env to Nuxt application file. We also add, require ( "dotenv") config ();. So that we can add to this profile process.env.API_KEY it. We have to do it, so we do not have to check in .env file. Inside env part, we have apiKey: process.env.API_KEY || "", which is dotenv by using the read .env file API KEY obtained.

In the router, we define dynamic routing, so that when a user clicks a link has given URL or click a link with such URL can view them. Nuxt also use these routes to generate static files. In generate, we define the path traversed Nuxt to generate static files static website. In this case, an array of routes by the routing of the title of the page we created earlier composition. It will iterate through them to get their data, and then render them and generate a file from the results of rendering. Folder structure will correspond to the route. Therefore, since we path is / headlines /: countryCode, thus generated artifacts will have the headlines folder and all the country / region code as the name of the sub-folders, and files in each folder there will be a presentation with index.html Content.

Now, we are ready to deploy our web site to Netlify. By going to https://www.netlify.com/create a Netlify account. Free program will meet our needs. Managed code is then submitted to the Git repository on GitHub, Gitlab or the Bitbucket. Then, when you log Netlify, click Git in New site. From there, you can add hosted one of these services in the Git repository. Then, when asked to enter Build Command, input node ./create-env.js && npm run generate, will publish the directory dist.

After that, .env file API key entered in the "Environment Variables" section of the site settings, you can "build and deploy", "Environment" on the menu by clicking the link to enter. API_KEY input as the key, and enter key as News API API value. Then click the Save button.

Once all the contents submitted and pushed to GitHub, Gitlab Bitbucket or hosted Git repository, Netlify will automatically build and deploy.

Original link: https://dev.to/aumayeung/generate-static-websites-with-nuxt-1ia1

Guess you like

Origin www.cnblogs.com/yzsunlei/p/12159076.html