Kako brzo postaviti postupak izrade statičnog mjesta

Imate statičku web stranicu koja je sve implementirana i spremna da je svijet vidi, ali gdje biste je trebali smjestiti? Kako odabrati pravu platformu i planirati skup statičnih datoteka? Kako možete osigurati da se web stranica automatski obnavlja kad god promijenite njezin sadržaj?

U ovom članku pokazat ću vam kako generirati statično web mjesto, postaviti automatski postupak izrade koji se pokreće promjenama sadržaja i rasporediti web mjesto na javni poslužitelj.

Uvod

U prethodnim člancima objasnio sam kako izraditi dinamično JavaScript web mjesto sa sadržajem iz bezglavog CMS-a Kentico Cloud. Tada sam vam pokazao kako ga pretvoriti u statično web mjesto radi poboljšanja performansi, sigurnosti i SEO-a. Dakle, vrijeme je da generiramo tu web lokaciju i stavimo je na mrežu da je vidi cijeli svijet.

Generiranje statičnog mjesta

Svaki statički generator web stranica omogućuje vam lokalnu izradu stranice bez generiranja svih datoteka nakon svake promjene datoteke. Ako ste slijedili moje članke, na Vue.js-u imate web mjesto koje je pretvoreno da koristi Nuxt.js kao okvir, ali i dalje zahtijeva razvojni poslužitelj za obradu zahtjeva za web stranice. Da biste generirali statičke datoteke, pokrenite sljedeću naredbu:

npx nuxt generate

Otvorite distmapu u korijenu vašeg projekta da biste pronašli generirane datoteke i provjerite je index.htmlli vaše web mjesto ispravno generirano. Imam običaj provjeravati i podređene stranice na kojima znam da postoji neki sadržaj iz bezglavog CMS-a, poput stranice bloga. Ako vidite sadržaj u HTML obliku, pobjednik ste!

Gdje bih trebao biti domaćin statičnom mjestu?

To je vjerojatno sljedeće pitanje koje postavljate nakon generiranja svih datoteka. Ako obnavljate web mjesto, a vaše je staro web mjesto i dalje na mreži, vjerojatno razmišljate o korištenju istog davatelja usluge za statičko web mjesto. To je sasvim u redu. Međutim, ako je vaša stara web lokacija izgrađena na vrhu tradicionalnog CMS-a ili drugog programskog jezika, možda ćete trebati dvaput razmisliti.

Vaš trenutni prostor za hosting prilagođen je potrebama drugog sustava ili dizajniran za podršku određenim postavkama, poput PHP-a i MySQL-a ili .NET-a i PostgreSQL-a. Dakle, ako je to slučaj, vjerojatno ste koristili količinu prometa, sesija i druge vrijednosti da biste izračunali koju količinu računalne snage ćete trebati (ili poput mene u prošlosti, samo sam se nadao da će biti u redu).

Sa statičkim web mjestima dolazi i olakšanje: nema složenijih formula, aproksimacija i profesionalnih nagađanja. Hostiranje hrpe statičnih datoteka nešto je što svaki web poslužitelj može učiniti lako. Najvažniji aspekt je da poslužitelj više ne mora prolaziti kroz sofisticirani cjevovod za obradu zahtjeva za svaki pogodak. Umjesto toga služi samo statičkim datotekama. A to je lako i brzo.

Hostiranje statičnih web stranica stoga je mnogo jeftinije. Postoje deseci usluga koje vam omogućuju besplatno hostiranje vaših web stranica ili barem besplatne početne planove. Oni uključuju:

  • GitHub stranice
  • Netlify
  • Heroku
  • i drugim globalnim i lokalnim davateljima usluga. Možete, naravno, koristiti i usluge hostinga globalnih web stranica poput Azure ili AWS.

Odlučio sam odabrati GitHub stranice jer su sva moja spremišta već hostirana na GitHubu. Također je potpuno besplatan i podržava prilagođene domene 2. razine.

Kako mogu izraditi i postaviti statično mjesto?

Ali nije stvar samo u hostingu. Internetske stranice je neophodno, ali jednako je važno razmišljati o cijelom procesu implementacije. Odnosno - kako će se generirati i transportirati statičke stranice na poslužitelj. Za prvu izradu možete generirati stranice u vašem lokalnom okruženju koristeći npx nuxt generatei kopirati i zalijepiti statičke datoteke u vaš hosting prostor putem FTP-a. Ali hoćete li ponoviti taj postupak svaki put kad dođe do promjene sadržaja?

Proces postavljanja statičkog mjesta sastoji se od tri dijela:

  1. Okidač
  2. Izgraditi
  3. Raspoređivanje

Okidač

Nova gradnja mora se dogoditi kada se dogodi bilo promjena sadržaja ili implementacije. To znači da kad god uređivač sadržaja objavi novi sadržaj u bezglavom CMS-u ili kada promijenite izvorni kod, web mjesto treba obnoviti. Ali kako to postići?

Okidač promjene sadržaja

Svaki zreli CMS bez glave sadrži web kuke. Oni predstavljaju obavijest o usluzi o određenoj vrsti radnje. Dakle, kada urednik objavi stavku sadržaja, CMS bez glave pokreće obavijest o webhook-u koja se šalje na definirani URL. U ovom slučaju na poslužitelj za izgradnju koji će postupiti po obavijesti i obnoviti web mjesto.

Ali kako graditelj poslužitelja zna što treba učiniti? Pa, nema pojma kakvu pohranu sadržaja koristite i vjerojatno ne bi razumio generičku obavijest o web-udici. Iz tog razloga u sredinu sam dodao jednostavnu Azure funkciju koja čini dvije stvari - prvo provjerava je li izvor obavijesti Kentico Cloud:

...
if (!isValidSignature(req, process.env['KC_WEBHOOK_SECRET'])) { context.log('Signature was invalid'); return;}
...
const isValidSignature = (req, secret) => { const givenSignature = req.headers['x-kc-signature']; const computedSignature = crypto.createHmac('sha256', secret) .update(req.rawBody) .digest();
 return crypto.timingSafeEqual(Buffer.from(givenSignature, 'base64'), computedSignature);}

(pogledajte kompletnu datoteku na GitHubu)

i zatim okida izgradnju pomoću API-ja poslužitelja za izgradnju:

request.post({ url: "//api.travis-ci.org/repo/Kentico%2Fkentico.github.io/requests", headers: { "Content-Type": "application/json", "Accept": "application/json", "Travis-API-Version": "3", "Authorization": `token ${process.env['TRAVIS_TOKEN']}` },
...

(pogledajte kompletnu datoteku na GitHubu)

I know I know, Azure asks you for your credit card before you can create functions. But you can use Webtask.io, which is completely free. I explained how to create a simple function there in one of my previous articles.

Code change trigger

With code, the process gets even easier. The build servers often offer direct integration with GitHub, so it is just a matter of authorizing the build server with GitHub. When you push your code change into a remote repository, the build server receives the information automatically, and based on its configuration triggers a new build.

Build

I know, the words “build server” sounds so complicated and expensive. But when you think about it, the only thing a build server needs to do for you is to generate pages and deploy them. Exactly what you did manually with one npx command and copy-paste operation. And that was not that hard, was it?

So how can you decide which build server to use? First, you need to choose whether you want to run the build locally on your server or remotely on a third-party service. I don’t have a local server I could use for this purpose, so I decided to use third-party services. These services include:

  • AppVeyor
  • Travis CI

Both of these services are free for open-source projects.

“What? Is my website open-source? This guy is crazy!”

Am I? :-) I already mentioned the benefits of open-sourcing your website implementation in my previous article about security. In most cases, websites are very similar in functionality, so there is probably no special know-how in your implementation. It’s the content that holds the value.

But let’s get back to the build server. I chose Travis CI as it was recommended to me by a colleague. We use it for many GitHub projects in our company. So how long does it take to set it up?

Initially, I was expecting a complicated UI to configure all aspects of a build within Travis (remember VSTS online?), so finding out it all sits in a single file was a relief. So the first thing you need to do is create a file #.travis.yml# in the root of your project. This file defines what is happening during a build.

dist: trusty language: node_js node_js: — "stable" before_script: — npm install script: — npm run build deploy: ...
packages.json:"scripts": { ... "build": "npx nuxt generate && cpx CNAME dist", ...}

You see it is straightforward to understand. First I instruct NPM to install all required packages as a prerequisite to running a build. Then all static files are generated into a dist folder — this is the default when using Nuxt. I also included a preview of a packages.json file, which defines build script. Note that I am also copying CNAME file to dist directory — this tells GitHub Pages I am using custom domain rather than github.io.

Deployment

Finally the last part of the whole process. We have files generated, and now we need to transfer them to our hosting space, just like we did before using FTP. This is yet another thing a build server can do for you.

As I mentioned before I have chosen GitHub Pages as my host and Travis CI as a build server. Travis provides many options for automated deployments including GitHub Pages, so the configuration was a piece of cake. Take a look at the deployment configuration:

deploy: local-dir: dist target-branch: master provider: pages skip-cleanup: true github-token: $GITHUB_TOKEN keep-history: true verbose: true on: branch: source

Local-dir defines where my generated static pages are, target-branch marks a branch in the GitHub repository to deploy to, and pages is the name of the Travis provider for GitHub Pages. To deploy successfully you also need to generate and provide a github-token. You see there is just a variable in the build configuration as the file sits in public repository. The token’s value is stored in repository settings in Travis UI.

The finale of the series

And that’s it. That’s all you need to trigger, build, and deploy a static site automatically. Without any previous experience with build and deployment processes, this should not take you longer than a few hours. You see, static sites can be very dynamic in terms of content, the actual static file generating is handled automatically without a single human effort.

During this series of articles, I explained how to build a website using Content-as-a-Service (CaaS) to store your content, how to ensure your website is secure by not using any database, and how to ensure such a website still contains dynamic functionality like form submissions.

Good luck with your new static websites and have a #staticNewYear!

Other articles in the series:

  1. How to start creating an impressive website for the first time
  2. How to decide on the best technology for your website?
  3. How to power up your website with Vue.js and minimal effort
  4. How to Mix Headless CMS with a Vue.js Website and Pay Zero
  5. How to Make Form Submissions Secure on an API Website
  6. Building a super-fast and secure website with a CMS is no big deal. Or is it?
  7. How to generate a static website with Vue.js in no time
  8. How to quickly set up a build process for a static site