天天看點

[技術翻譯]使用Nuxt生成靜态網站

本周再來翻譯一些技術文章,本次預計翻譯三篇文章如下:

  • 04.[譯]使用Nuxt生成靜态網站(Generate Static Websites with Nuxt)
  • 05.[譯]Web網頁内容是如何影響電池功耗的(How Web Content Can Affect Power Usage)
  • 06.[譯]在現代JavaScript中編寫異步任務(https://web.dev/off-main-thread/)
我翻譯的技術文章都放在一個github倉庫中,如果覺得有用請點選star收藏。我為什麼要建立這個git倉庫?目的是通過翻譯國外的web相關的技術文章來學習和跟進web發展的新思想和新技術。git倉庫位址:https://github.com/yzsunlei/javascript-article-translate

靜态網站如今再次流行起來了。資訊站和品牌宣傳站不再需要使用WordPress之類的内容管理系統來動态更新。

使用靜态網站生成器,您可以從無源CMS,API等動态源以及Markdown檔案等檔案中擷取内容。

Nuxt是基于Vue.js的出色的靜态網站生成器,可輕松用于建構靜态網站。使用Nuxt,從動态内容建構靜态網站所需要做的就是建立模闆,以從API和Markdown檔案等動态源動态顯示内容。然後,在Nuxt配置檔案中,我們靜态定義路由,以便它可以通過相同的路由将内容生成為靜态檔案。

在本文中,我們将使用Nuxt建構新聞網站,并将使用

https://newsapi.org/

的News API 作為内容。您必須先了解Vue.js,然後才能使用Nuxt建立網站,因為Nuxt是基于Vue.js的架構。

首先,我們在News API網站上注冊API密鑰。如果我們隻想擷取頭條新聞,它是免費的。我們開始來使用Nuxt CLI建構網站。我們通過鍵入以下指令來運作:

npx create-nuxt-app news-website
           

這将在news-website檔案夾中建立初始項目檔案。運作該向導時,我們不為伺服器端架構選擇任何内容,不為UI架構選擇任何内容,不為測試架構選擇任何内容,不為Nuxt模式選擇通用檔案,最後根據您的情況選擇是否包含Axios請求庫,使用lint進行代碼整理和prettify進行代碼美化。

接下來,我們需要安裝一些軟體包。我們需要

@nuxtjs/dotenv

用于在本地讀取環境變量的程式包和

country-list

用于在我們的網站上擷取國家清單的庫。要安裝它們,我們運作:

npm i @nuxtjs/dotenv country-list
           

現在我們可以開始建立我們的網站了。在default.vue檔案中,我們将現有代碼替換為:

<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="#" target="_blank" rel="external nofollow" 
              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>
           

這是用于定義我們網站布局的檔案。我們在此處添加了Bootstrap導航欄。該欄包含首頁連結和國家清單的下拉清單。這些nuxt-link元件都是指向頁面的連結,這些頁面用于在生成靜态檔案時擷取國家/地區的标題。可以通過調用函數從該部分的country-list包中擷取國家。在本節中,我們通過覆寫類的預設顔色來更改導航欄的背景顔色。本部分底部的元件将顯示我們的内容。

scriptgetDatastyle.bg-lightnuxttemplate
           

接下來,我們建立一個mixins檔案夾并建立一個名為requestsMixin.jsfile的檔案。在其中,我們添加:

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}`  
      );  
    }  
  }  
};
           

該檔案包含用于從News API擷取按國家/地區和關鍵字作為标題的代碼。

然後,在pages檔案夾中,我們建立headlines檔案夾,然後在檔案headlines夾中,建立_countryCode.vue檔案。在檔案中,我們添加:

<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" rel="external nofollow"  target="_blank" rel="external nofollow"  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>
           

在該檔案中,我們接受route參數,countryCode然後從該位置調用我們之前制作并包含在此元件中的

this.getHeadlines

函數,requestsMixin以從News API擷取标題。然後結果将顯示在該template部分的Bootstrap卡中。在模闆中,我們通過從country-list資料中找到國家名稱來獲得國家名稱。如果找不到标題,我們會顯示一條消息。通常,如果要制作一個接受URL參數的頁面,則必須制作一個帶有下劃線作為第一個字元以及所需URL參數的變量名的檔案。是以,在此示例中,_countryCode.vue中我們将countryCode使用該參數

this.$route.params.countryCode

接下來,index.vue在pages檔案夾中,将現有代碼替換為:

<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" rel="external nofollow"  target="_blank" rel="external nofollow"  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>
           

這使我們可以在首頁上顯示美國的标題。它的工作原理與_countryCode.vue頁面相似,不同之處在于,我們僅獲得美國的頭條新聞,而不接受URL參數來根據URL獲得來自不同國家/地區的頭條新聞。

接下來,我們create-env.js在項目的根檔案夾中建立一個,并添加以下内容:

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

這使我們可以部署到Netlify,因為我們需要.env根據輸入的環境變量動态建立檔案。另外,我們.env手動建立檔案,然後将API_KEY鍵作為鍵,将News API API鍵作為值。

接下來的nuxt.config.js,我們将現有代碼替換為:

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}`);  
    }  
  }  
};
           

在head對象中,我們更改了title以便顯示所需的标題而不是預設标題。在link中,我們添加了Bootstrap CSS,在script中,我們添加了Bootstrap JavaScript檔案和jQuery,它們是Bootstrap的依賴項。由于我們要建構靜态站點,是以不能使用BootstrapVue,因為它是動态的。我們不希望在生成的輸出中使用任何動态JavaScript,是以我們必須使用普通的Bootstrap。在modules中,我們添加"@nuxtjs/dotenv"了從.env建立到Nuxt應用程式的檔案中讀取環境變量的功能。我們還進行了添加,require(“dotenv”).config();以便我們可以将process.env.API_KEY其添加到此配置檔案中。我們必須這樣做,是以我們不必檢入.env檔案。在裡面env部分,我們有了apiKey: process.env.API_KEY || “”,這是通過使用讀取.env檔案中的API KEY而獲得的dotenv。

在router中,我們定義了動态路由,以便當使用者單擊具有給定URL的連結或單擊具有此類URL的連結時可以檢視它們。Nuxt還使用這些路由來生成靜态檔案。在generate中,我們定義了Nuxt周遊的路徑,以生成靜态網站的靜态檔案。在這種情況下,路由數組由我們之前建立的标題頁面的路由組成。它将周遊它們以擷取它們的資料,然後渲染它們并從渲染的結果生成檔案。檔案夾結構将與路線相對應。是以,由于我們path是/headlines/:countryCode,是以生成的工件将具有該headlines檔案夾以及所有國家/地區代碼作為子檔案夾的名稱,并且在每個檔案夾内将有一個index.html 與呈現的内容。

現在,我們準備将我們的網站部署到Netlify。通過轉到

https://www.netlify.com/

建立一個Netlify帳戶。免費計劃将滿足我們的需求。然後将代碼送出到托管在GitHub,Gitlab或Bitbucket上的Git存儲庫。然後,當您登入Netlify時,單擊Git中的New site。從那裡,您可以添加托管在其中一項服務中的Git存儲庫。然後,當要求您輸入Build Command時,輸入

node ./create-env.js && npm run generate

,釋出目錄将為dist。

之後,将.env檔案中的API密鑰輸入到網站設定的“環境變量”部分,您可以通過單擊“建構和部署”菜單上的“環境”連結來進入。輸入API_KEY作為密鑰,然後輸入News API API密鑰作為值。然後單擊儲存按鈕。

一旦将所有内容送出并推送到由GitHub,Gitlab或Bitbucket托管的Git存儲庫中,Netlify将自動建構和部署。

原文連結:https://dev.to/aumayeung/generate-static-websites-with-nuxt-1ia1