本周再來翻譯一些技術文章,本次預計翻譯三篇文章如下: "04.[譯]使用Nuxt生成靜態網站" ( "Generate Static Websites with Nuxt" ) "05.[譯]Web網頁內容是如何影響電池功耗的" ( "How Web Content Can Affect Power ...
本周再來翻譯一些技術文章,本次預計翻譯三篇文章如下:
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="#"
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