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


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

我翻譯的技術文章都放在一個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="#"
              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" 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" 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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM