日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

[技術(shù)翻譯]使用Nuxt生成靜態(tài)網(wǎng)站

 看見就非常 2020-07-14

本周再來翻譯一些技術(shù)文章,本次預(yù)計(jì)翻譯三篇文章如下:

我翻譯的技術(shù)文章都放在一個(gè)github倉庫中,如果覺得有用請(qǐng)點(diǎn)擊star收藏。我為什么要?jiǎng)?chuàng)建這個(gè)git倉庫?目的是通過翻譯國(guó)外的web相關(guān)的技術(shù)文章來學(xué)習(xí)和跟進(jìn)web發(fā)展的新思想和新技術(shù)。git倉庫地址:github.com/yzsunlei/ja…

靜態(tài)網(wǎng)站如今再次流行起來了。信息站和品牌宣傳站不再需要使用WordPress之類的內(nèi)容管理系統(tǒng)來動(dòng)態(tài)更新。

使用靜態(tài)網(wǎng)站生成器,您可以從無源CMS,API等動(dòng)態(tài)源以及Markdown文件等文件中獲取內(nèi)容。

Nuxt是基于Vue.js的出色的靜態(tài)網(wǎng)站生成器,可輕松用于構(gòu)建靜態(tài)網(wǎng)站。使用Nuxt,從動(dòng)態(tài)內(nèi)容構(gòu)建靜態(tài)網(wǎng)站所需要做的就是創(chuàng)建模板,以從API和Markdown文件等動(dòng)態(tài)源動(dòng)態(tài)顯示內(nèi)容。然后,在Nuxt配置文件中,我們靜態(tài)定義路由,以便它可以通過相同的路由將內(nèi)容生成為靜態(tài)文件。

在本文中,我們將使用Nuxt構(gòu)建新聞網(wǎng)站,并將使用https:///的News API 作為內(nèi)容。您必須先了解Vue.js,然后才能使用Nuxt建立網(wǎng)站,因?yàn)镹uxt是基于Vue.js的框架。

首先,我們?cè)贜ews API網(wǎng)站上注冊(cè)API密鑰。如果我們只想獲取頭條新聞,它是免費(fèi)的。我們開始來使用Nuxt CLI構(gòu)建網(wǎng)站。我們通過鍵入以下命令來運(yùn)行:

npx create-nuxt-app news-website復(fù)制代碼

這將在news-website文件夾中創(chuàng)建初始項(xiàng)目文件。運(yùn)行該向?qū)r(shí),我們不為服務(wù)器端框架選擇任何內(nèi)容,不為UI框架選擇任何內(nèi)容,不為測(cè)試框架選擇任何內(nèi)容,不為Nuxt模式選擇通用文件,最后根據(jù)您的情況選擇是否包含Axios請(qǐng)求庫,使用lint進(jìn)行代碼整理和prettify進(jìn)行代碼美化。

接下來,我們需要安裝一些軟件包。我們需要@nuxtjs/dotenv用于在本地讀取環(huán)境變量的程序包和country-list用于在我們的網(wǎng)站上獲取國(guó)家列表的庫。要安裝它們,我們運(yùn)行:

npm i @nuxtjs/dotenv country-list復(fù)制代碼

現(xiàn)在我們可以開始建立我們的網(wǎng)站了。在default.vue文件中,我們將現(xiàn)有代碼替換為:

<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>復(fù)制代碼

這是用于定義我們網(wǎng)站布局的文件。我們?cè)诖颂幪砑恿薆ootstrap導(dǎo)航欄。該欄包含主頁鏈接和國(guó)家列表的下拉列表。這些nuxt-link組件都是指向頁面的鏈接,這些頁面用于在生成靜態(tài)文件時(shí)獲取國(guó)家/地區(qū)的標(biāo)題??梢酝ㄟ^調(diào)用函數(shù)從該部分的country-list包中獲取國(guó)家。在本節(jié)中,我們通過覆蓋類的默認(rèn)顏色來更改導(dǎo)航欄的背景顏色。本部分底部的組件將顯示我們的內(nèi)容。

scriptgetDatastyle.bg-lightnuxttemplate復(fù)制代碼

接下來,我們創(chuàng)建一個(gè)mixins文件夾并創(chuàng)建一個(gè)名為requestsMixin.jsfile的文件。在其中,我們添加:

const APIURL = 'https:///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}` ); } } };復(fù)制代碼

該文件包含用于從News API獲取按國(guó)家/地區(qū)和關(guān)鍵字作為標(biāo)題的代碼。

然后,在pages文件夾中,我們創(chuàng)建headlines文件夾,然后在文件headlines夾中,創(chuàng)建_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>復(fù)制代碼

在該文件中,我們接受route參數(shù),countryCode然后從該位置調(diào)用我們之前制作并包含在此組件中的this.getHeadlines函數(shù),requestsMixin以從News API獲取標(biāo)題。然后結(jié)果將顯示在該template部分的Bootstrap卡中。在模板中,我們通過從country-list數(shù)據(jù)中找到國(guó)家名稱來獲得國(guó)家名稱。如果找不到標(biāo)題,我們會(huì)顯示一條消息。通常,如果要制作一個(gè)接受URL參數(shù)的頁面,則必須制作一個(gè)帶有下劃線作為第一個(gè)字符以及所需URL參數(shù)的變量名的文件。因此,在此示例中,_countryCode.vue中我們將countryCode使用該參數(shù)this.$route.params.countryCode。

接下來,index.vue在pages文件夾中,將現(xiàn)有代碼替換為:

<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>復(fù)制代碼

這使我們可以在主頁上顯示美國(guó)的標(biāo)題。它的工作原理與_countryCode.vue頁面相似,不同之處在于,我們僅獲得美國(guó)的頭條新聞,而不接受URL參數(shù)來根據(jù)URL獲得來自不同國(guó)家/地區(qū)的頭條新聞。

接下來,我們create-env.js在項(xiàng)目的根文件夾中創(chuàng)建一個(gè),并添加以下內(nèi)容:

const fs = require('fs')  fs.writeFileSync('./.env', `API_KEY=${process.env.API_KEY}`)復(fù)制代碼

這使我們可以部署到Netlify,因?yàn)槲覀冃枰?env根據(jù)輸入的環(huán)境變量動(dòng)態(tài)創(chuàng)建文件。另外,我們.env手動(dòng)創(chuàng)建文件,然后將API_KEY鍵作為鍵,將News API API鍵作為值。

接下來的nuxt.config.js,我們將現(xiàn)有代碼替換為:

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./bootstrap/4.0.0/css/bootstrap.min.css' } ], script: [ { src: 'https://code./jquery-3.3.1.slim.min.js' }, { src: 'https://cdnjs./ajax/libs/popper.js/1.14.7/umd/popper.min.js' }, { src: 'https://stackpath./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./usage '@nuxtjs/axios', '@nuxtjs/dotenv' ], /* ** Axios module configuration ** See https://axios./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}`); } } };復(fù)制代碼

在head對(duì)象中,我們更改了title以便顯示所需的標(biāo)題而不是默認(rèn)標(biāo)題。在link中,我們添加了Bootstrap CSS,在script中,我們添加了Bootstrap JavaScript文件和jQuery,它們是Bootstrap的依賴項(xiàng)。由于我們要構(gòu)建靜態(tài)站點(diǎn),因此不能使用BootstrapVue,因?yàn)樗莿?dòng)態(tài)的。我們不希望在生成的輸出中使用任何動(dòng)態(tài)JavaScript,因此我們必須使用普通的Bootstrap。在modules中,我們添加'@nuxtjs/dotenv'了從.env創(chuàng)建到Nuxt應(yīng)用程序的文件中讀取環(huán)境變量的功能。我們還進(jìn)行了添加,require('dotenv').config();以便我們可以將process.env.API_KEY其添加到此配置文件中。我們必須這樣做,所以我們不必檢入.env文件。在里面env部分,我們有了apiKey: process.env.API_KEY || '',這是通過使用讀取.env文件中的API KEY而獲得的dotenv。

在router中,我們定義了動(dòng)態(tài)路由,以便當(dāng)用戶單擊具有給定URL的鏈接或單擊具有此類URL的鏈接時(shí)可以查看它們。Nuxt還使用這些路由來生成靜態(tài)文件。在generate中,我們定義了Nuxt遍歷的路徑,以生成靜態(tài)網(wǎng)站的靜態(tài)文件。在這種情況下,路由數(shù)組由我們之前創(chuàng)建的標(biāo)題頁面的路由組成。它將遍歷它們以獲取它們的數(shù)據(jù),然后渲染它們并從渲染的結(jié)果生成文件。文件夾結(jié)構(gòu)將與路線相對(duì)應(yīng)。因此,由于我們path是/headlines/:countryCode,因此生成的工件將具有該headlines文件夾以及所有國(guó)家/地區(qū)代碼作為子文件夾的名稱,并且在每個(gè)文件夾內(nèi)將有一個(gè)index.html 與呈現(xiàn)的內(nèi)容。

現(xiàn)在,我們準(zhǔn)備將我們的網(wǎng)站部署到Netlify。通過轉(zhuǎn)到https://www./創(chuàng)建一個(gè)Netlify帳戶。免費(fèi)計(jì)劃將滿足我們的需求。然后將代碼提交到托管在GitHub,Gitlab或Bitbucket上的Git存儲(chǔ)庫。然后,當(dāng)您登錄Netlify時(shí),單擊Git中的New site。從那里,您可以添加托管在其中一項(xiàng)服務(wù)中的Git存儲(chǔ)庫。然后,當(dāng)要求您輸入Build Command時(shí),輸入node ./create-env.js && npm run generate,發(fā)布目錄將為dist。

之后,將.env文件中的API密鑰輸入到網(wǎng)站設(shè)置的“環(huán)境變量”部分,您可以通過單擊“構(gòu)建和部署”菜單上的“環(huán)境”鏈接來進(jìn)入。輸入API_KEY作為密鑰,然后輸入News API API密鑰作為值。然后單擊保存按鈕。

一旦將所有內(nèi)容提交并推送到由GitHub,Gitlab或Bitbucket托管的Git存儲(chǔ)庫中,Netlify將自動(dòng)構(gòu)建和部署。

原文鏈接:/aumayeung/g…

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多