Inspirirana istinitom pričom
Krenimo na putovanje ...
Zamislite da ste na popisu poziva za slobodnu agenciju u gradu po vašem izboru. Sada recimo da u pristiglu poštu dobijete lijepu poruku. Otvorite poruku i izgleda prilično normalno.
Imamo neposrednu potrebu da programer započne danas.poruka i izgleda prilično normalno.
Imamo neposrednu potrebu da programer započne danas.
Budući da ste osoba koja uživa jesti hranu da bi preživjela, upišete neke informacije i prijavite se.
U roku od pet minuta nakon što pritisnete taj gumb za slanje, dobit ćete poziv. 10 minuta nakon toga dobivate pristup poslužitelju.
Nepotrebno je reći da ste na zadnjem roku. Taj je rok do kraja dana.
Otvorite HTML datoteke i pogledate ih ... užasnuto.
Šifra je posvuda, neuredna i neorganizirana. Da ne spominjem, morate napraviti prilagodbe zaglavlja i podnožja ... na pet različitih stranica.
Prvo što napravite je da ga prođete kroz Prettify (Hvala bogu za Prettify). To je očistilo, ali ima još nekih problema. Ovo je statično HTML mjesto, što znači da ćete svaku promjenu u globalnim stvarima (zaglavlje, podnožje itd.) Morati kopirati u SVAKU datoteku. Oh moj.
Što ćeš napraviti???
Jednostavno, izradit ćete datoteku Webpack da biste se nosili sa glupim dijelom pisanja HTML-a i to ćete učiniti brzo.
Evo što će vam trebati biti poznato:
- Javascript! (zbog Webpacka)
- HTML! (jer je od toga napravljen internet)
- CSS! (jer tko voli ružne stvari?)
- mops! (jer je to poanta ovog članka!)
- npm (jer je Bog)
- Osnovno znanje naredbenog retka (jer raditi stvari putem preuzimanja je glupo ...)
- Znajte tko je Jim Carrey (jer gifovi)
Ako niste upoznati s mopsom, još uvijek možete upravljati svojim putem. Ali ako imate vremena, pročitajte ga. Preporučujem učenje mopsa s mopsovima. Ili njihovi dokumenti. Pretpostavljam da su i to u redu.
Evo verzija koje sam koristio za ovo:
- html-loader: 0.5.5,
- html-webpack-plugin: 3.2.0,
- pug-html-loader: 1.1.5,
- Web paket: 4.12.0
- webpack-cli: 3.0.8
- npm: 6.1.0
- čvor: 10.4.0
Ažuriranje: Napravio sam video! Provjerite ako ne želite čitati, već biste radije slušali moj glas 30 minuta.
Korak 1. Organizirajte strukturu projekta
Na ovaj način volim organizirati mapu za ove vrste projekata.
src/ oldHTML/ dist/ images/ css/ webpack.config
Volim sav izvorni HTML staviti u zasebnu mapu koju ne mogu slučajno izbrisati. Webpack je malo ljubazniji od recimo Gulpa, koji sam već izbrisao cijelu mapu? Ova je struktura dovoljno dobra da započnemo.
Korak 2. Povećajte broj okretaja u minuti
npm
Sa yarn
strane : Nedavno sam se vratio iz iz nekoliko razloga. Jedan od njih bio je da je prestao raditi i imao sam malo strpljenja da to ponovno uspije. Zanimljiv članak ovdje, ako želite pročitati više.
Svejedno, iniciraj taj npm.
npm init -y
Napomena: ( -y je ako ne želite odgovoriti ni na jedno od njegovih pitanja)
Instalirajte razvojne ovisnosti.
Ne brinite, objasnit ću vam svaku od njih.
npm install -D webpack webpack-cli pug-html-loader html-webpack-plugin html-loader
Dodajte neke skripte u paket.json
Prema zadanim postavkama package.json ima jednu skriptu, ali moramo dodati nekoliko.
"dev": "webpack --watch --mode development", "prod": "webpack --mode production"
To su dvije koje volim uključiti. Prvi će pokrenuti Webpack u razvojnom načinu (napomena: zastavica --mode nova je za Webpack 4) i nadgledati promjene datoteka. Drugo je kada želimo pokrenuti Webpack u proizvodnji, to obično umanjuje stvari.
To bi trebalo izgledati otprilike ovako:
"name": "pugTut", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "dev": "webpack --watch --mode development", "prod": "webpack --mode production" }, .....more code
Stvorite nekoliko početnih datoteka kako biste testirali našu konfiguraciju Webpack-a
Webpacku je potrebna ulazna točka, pa napravimo je. Izradite app.js u mapi src / . Može biti prazno. Nema veze. Također je potrebna početna datoteka mopsa za sastavljanje. Stvorite i datoteku index.pug u mapi src / .
Stvorite i postavite webpack.config.js u osnovnom direktoriju
U redu, ako prije niste koristili Webpack, proći ću kroz svaki dio pojedinačno kako bih vam (i nadam se i meni) dao ideju o wtf-u koji se događa u ovoj konfiguracijskoj datoteci.
Prvo, izjavimo svoje ovisnosti.
// webpack.config.js const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin');
path je matična ovisnost o čvoru, tako da ne biste trebali brinuti hoće li to biti potrebno u vašem package.json.
Webpack je, pa Webpack ...
HtmlWebpackPlugin je način na koji izdvajamo HTML. Nisam stručnjak za to kako Webpack radi. Koliko sam shvatio, budući da je dizajniran za konzumiranje JavaScript-a, u našoj konfiguracijskoj datoteci moramo imati utovarivače kako bi izvukli stvari poput HTML-a i CSS-a. HtmlWebpackPlugin je kako radimo nešto korisno s HTML-om koji se izvlači iz utovarivača.
Cool? Sljedeći korak…
const pug = { test: /\.pug$/, use: ['html-loader?attrs=false', 'pug-html-loader'] };
This method is used by Wes Bos and I really like it, so I use it. We have to define rules on how to handle certain file types, for example .pug or .css. Putting it into a variable makes it more legible, in my opinion. Anyways, we setup a test case with a regexp, then define the loaders we want to use. For whatever reason, the loaders are listed in reverse order of what you’d think. I’m sure there is an explanation but I couldn’t find it.
Confused? What that means is, if we want to use pug to compile to HTML, we write it in the order above: our html loader ->pug loader. However, in reality when the code runs, it runs the pug loader first…then the HTML loader. Yep.
Note: Don’t worry about ?attrs=false
for right now, I’ll explain it a bit later.
Cool? Next step…
const config = { entry: './src/app.js', output: { path: path.resolve(__dirname, 'dist'), filename: '[name].bundle.js' }, module: { rules: [pug] }, plugins: [ new HtmlWebpackPlugin({ filename: 'index.html', template: 'src/index.pug', inject: false }) ] }; module.exports = config;
Holy Crap. That’s a lot of stuff. Let’s break it down.
entry is simply the entry point for our JS file.
output defines where we want our JS file to go. This is not where our HTML files will go. As mentioned above, path is a node module. __dirname is a variable we can get from Node. The filename is what we want to call our JS file. The [name]
is a substitution. In this case, it uses the file name of the entry file. You can also use [hash]
if you want a unique identifier.
module defines the different modules. For the purpose of this tutorial, there is only one module with one set of rules. rules defines the rules we will use for that module. We throw the pug variable we made earlier into there. So nice, so clean.
Finally, plugins is where we get to add any third party stuff. In our case, we are using HtmlWebpackPlugin to do something with our pug files.
filename is what we want our HTML file to be called. template is the pug file that are compiling. inject is: “inject all assets into the given template.” I have it set to false because…well, honestly I don’t remember.
One of the crappiest things about HtmlWebpackPlugin is that you have to create an entry for EVERY HTML file. I tried to figure a way around it, but found no simple solutions.
// webpack.config.js const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const pug = { test: /\.pug$/, use: ['html-loader?attrs=false', 'pug-html-loader'] }; const config = { entry: './src/app.js', output: { path: path.resolve(__dirname, 'dist'), filename: '[name].bundle.js' }, module: { rules: [pug] }, plugins: [ new HtmlWebpackPlugin({ filename: 'index.html', template: 'src/index.pug', inject: false }) ] }; module.exports = config;
Before we move on, let’s make sure our code works! Run the script.
npm run dev
If all went well, you should see something like this:

We’ve come a long way. Here’s a present:
Step 3. Break up the pages into partials
This is where magic starts happening. I know it seems like we’ve been working for a while with very little gain, but trust me…it was worth it.
One of the most important features for pug is the partials. The idea is to have one file that holds most of your global code (head, header, footer, nav, and so on) and have individual files for all your content.
Let’s make a couple files. You should have created the index.pug file already, but let’s make one more, layout.pug.
src/ - index.pug - layout.pug
Step 4. Setup layout file
The layout file is basically the main template for your whole site. It will have hold all the global stuff, for example head, header and footer.
//- layout.pug doctype html html head title I'm a title body block header block content block footer script(src="somescript.js")
I guess something to explain is that pug is all based on indentation, similar to YAML. It is glorious, because that means no more closing tags! However, this can throw some, especially those with crappy indentation to begin with. So just make sure to start slow and make sure everything is indented correctly and you’ll be fine.
Looking at our layout.pug file, you’ll see some familiar HTML tags mixed with unfamiliar ones. I highly suggest downloading syntax highlighting for pug in your editor of choice. If you’re using VSCode, it should come with it by default. Thanks Microsoft.
I think it’s pretty easy to figure out, but let’s take a look at the meat of the document to make sure we know what’s going on.
head title I'm a title body block header block content block footer script(src="somescript.js")
head, body, title and script are normal tags, but what the hell is block? block is how we define dynamic content. Basically, this is telling pug that some content is going to go in here. Hopefully it’ll make more sense when we create our individual page files.
Step 5. Create more partials
Let’s make use of that index.pug file.
//- index.pug extends layout block content p Woah.
Looking at our index file, it seems awfully small for a whole HTML page. That’s because of that little extends fella. extends tells pug that you want to use another pug file as the template, in our case layout. Then below that block content is in reference to what we put in our layout.pug file.
If you have your Webpack still running in the background, it should recompile and you’ll get a fresh new index.html in your dist/ folder. If not, run Webpack again.
Step 6. Grab all the old HTML
Those starter files are fine and dandy, but we need to make some real progress. We need to start grabbing that HTML and using it! Luckily, pug will recognize regular old HTML tags, so you can literally copy all the HTML content you want and just paste it in there.
It might look something like this:
extends layout block content blerb
Woah.
Alright, it’s not really that simple.
Like I mentioned, pug is based on indentation. To make life easier on yourself, I suggest removing all indentation from the HTML file before pasting into the pug file. It will mostly work, but you’ll probably have to finagle it a bit. Lucky for us, pug-html-loader will tell us what’s wrong with it when it tries to compile. There are some examples of common problems in the next Step.
Step 7. Start optimizing
Neću lagati, kad prvi put ubacite HTML, Webpacku se to neće svidjeti. Evo nekoliko stvari na koje morate paziti:
Slike
- Provjerite jesu li veze do slika dobre. Iz bilo kojeg razloga, često ne uspije ako je src = "images /" umjesto src = "/ images /"
2. Obećao sam ranije da ću se vratiti na ono što je ?attrs=false
bilo, eto nas!
Ovo je objašnjenje sa stranice html-loader koje objašnjava što to čini.
Da biste potpuno onemogućili obradu atributa oznaka (na primjer, ako radite s učitavanjem slika na strani klijenta), možete pristupitiattrs=false
.
html-loader?attrs=false
Javascript
mops se ne igra lijepo s JS-om u oznakama skripti. Ako lijepite u redovno otvaranje i zatvaranje oznaka JS skripte, možda će to uspjeti. Međutim, ako želite koristiti oznaku skripte mops, samo dodajte točku na kraju, poput ove:
Step 8. Make more pages and start converting to pug tags
Clearly it’s useless if you are only doing the index page. For whatever you’re doing, just create a new file for each page you want. Also, make sure to make new HtmlWebpackPlugin entries in the plugins section in Webpack.
It’ll end up looking like this:
//webpack.config.js ...previous code... plugins: [ new HtmlWebpackPlugin({ filename: 'index.html', template: 'src/index.pug', inject: false }), new HtmlWebpackPlugin({ filename: 'contact.html', template: 'src/contact.pug', inject: false }) ] ...more code...
You don’t have to convert everything to pug format immediately. In fact, if you have a huge site with a crap ton of HTML, then you can do it as you go, but it does make it easier.
Includes
This wouldn’t be a very good tutorial if we didn’t talk about includes. Remember those blocks in the layout file? Well, if you don’t want the layout file to be giant, you can create separate files that will be pulled in at compile time. For instance, if you want to make a single file that holds all the header info. Breaking it up this way also helps substantially with indentation.
Create a new file “header” in a new folder “includes”:
src/ -- includes/ header.pug
In that file, put whatever you want to be in the header.
//- header.pug header h1 I'm a header
Now go back to layout.pug and include it.
//- layout.pug doctype html html head title I'm a title body block header include includes/header block content block footer script(src="somescript.js")
Step 7. Want to get Fancy?
There’s a ton more stuff you can do with pug and webpack. However, I think we’ve reached the end of the basics. Still, check out mixins. Those things are amazing.
Wrapping Up
I highly suggest bringing in HTML slowly, otherwise you’ll end up debugging 1,000 errors at once.