Scurt tutorial de webpack

Stefanescu Mihai 9 months ago iNoob

Tool-urile de build au ajuns sa fie o parte foarte importanta a dezvoltarii web, unul dintre motive fiind complixitatea din ce in ce mai mare a aplicatiilor JavaScript. Bundler-urile ne permit sa "impachetam", compilam si sa organizam asset-urile si librariile necesare unei aplicatii web.

In acest articol ne vom uita la webpack, un bundler si preprocesor open-source  ce poate face o varietate mare de lucruri. O sa vedem cum putem scrie module, cod de bundle si cum putem folosi plugin-uri.

De ce webpack?

Pentru ca suntem in web, nu exista un standard referitor la tool-ul de build folosit. Acum, dezvoltatorii au de ales intre tool-uri precum webpack, Gulp, Browserify, NPM Scripts, Grunt si multe altele. Sigur, putem compara toate aceste tool-uri si s-au scris o multime de astfel de articole, dar la final si preferinta personala are un cuvant de spus.

Am sa scriu aici o lista de argumente pro si contra webpack:

Pro:

- Functioneaza foarte bine cu aplicatii de tip Single Page Application
- Accepta atat require() cat si import
- Poti face code splitting avansat
- Hot Reload

Con:
- Nu-i chiar usor de inteles pentru incepatori
- Lucrul cu CSS, imagini sau alte fisiere non-JS poate fi putin mai greu la inceput
- Documentatia ar putea fi mai buna

Instalarea

Cel mai usor mod de a instala webpack este cu ajutorul unui manager de pachete. In acest tutorial o sa folosim npm dar la fel de usor puteti folosi si Yarn sau altceva. In ambele cazuri veti avea nevoie de Node.js instalat pe masina.

Eu prefer sa il instalez local, fara tag-ul -g. Astfel ma asigur ca oricine mai lucreaza pe acelasi proiect ca mine are aceasi versiune.

npm install webpack --save-dev

Dupa ce am rulat comanda de mai sus in folder-ul in care vrem sa ne incepem proiectul. Acum, hai sa ne definim scripturile de rulare in package.json:

"scripts": {
	"build": "webpack -p",
	"watch": "webpack --watch"
},

Acum, daca rulam npm run build din terminal webpack ne se va ocupa de bundle-uirea fisierelor noastre (tag-ul -p vine de la production si ne va minifica fisierele). Daca rulam npm run watch pornim un proces ce va urmari modificarile din fisierele nastre si va porni la fiecare modificare.

Acum, trebuie sa ii spunem de ce fisiere trebuie sa se ocupe, iar cel mai bine facem asta cu un fisier de config.

Fisierul de config

Acum o sa facem un fisier de config, desi o sa para relativ simplu, acest config poate face mult mai multe chestii.

In folder-ul proiectului tau trebuie sa faci in fisier webpack.config.js cu urmatoarele:

var path = require('path');

module.exports = {
  entry: './assets/js/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  }
};

Daca ne uitam in module.exports observam cheita entry, care ii spune webpack-ului care este fisierul js principal al proiectului nostru. bineinteles, exista mai multe strategii pentru definirea entry point-urilor, dar in masjoritatea cazurilor un singur entry point este suficient.

Apoi avem cheita output, in ii specificam numele si calea catre bundle-ul pe care trebuie sa il genereze. Acest bundle.js este singurul fisier javascript pe care il vom folosi in HTML:

<script src="./dist/bundle.js"></script>

Module webpack

Webpack ne permite sa lucram in mai multe moduri cu modulele, dar de cele mai multe ori esti liber sa le folosesti cum vrei.

Acum, hai sa adaugam un modul care sa salute utilizatorii. O sa facem un fisier greeter.js si o sa il exportam intr-o functie:

function greet() {
	console.log("Salutare si bun venit pe invata-programare.ro");
}

export default greet;

Acum, pentru a il folosi trebuie sa il importam in entrypoint, care va fi in /assets/js/index.js

import greet from './greeter.js';

console.log("I'm the entry point");
greet();

Acum, daca rulam npm run build si deschidem fisierul HTML in browser o sa vedem in consola aceste mesaje:

Entry point-ul nostru si fisierul greeter.js au fost compilate intr-un singur fisier numit bundle.js care in cele din urma a ajuns sa fie executat de browser:

Folosirea librariilor

Acum, hai sa presupunem ca atunci cand saluam un utilizator vrem sa ii aratam si ce zi a saptamani este. Pentru a face acest lucru o sa folosim o librarie numita moment.js

Prima data trebuie sa instalam libraria folosind npm:

npm install moment --save

Apoi, in fisierul creat mai devreme, greeter.js importam libraria si o folosim:

import moment from 'moment';

function greet() {
    var day = moment().format('dddd');
    console.log('Have a great ' + day + '!');
};

export default greet;

Dupa ce rulam npm run build o sa vedem urmatorul lucru in consola:

Loaders

Acesta este modul webpack-ului de a executa diverse actiuni in timpul bundleing-ului sau pre/post proceseze fisierele. De exemplu, poate compila TypeScript, sa incarce componente de Vue.js, sa randeze template-uri si multe altele.
Majoritatea loaderelor sunt scrise de comunitate, dar daca vreti o lista cu cele mai populare o gasiti aici.

Presupunand ca vrem sa folosim un linter in proiectul nostru pentru a verifica daca avem erori. Putem folosi JSHint loader.

Prima data trebuie sa instalam JSHint si JSHint loader:

npm install jshint jshint-loader --save-dev

Dupa ce am rulat aceasta comanda trebuie sa modificam fisierul config, unde vom initializa loader-ul si ii vom spune al ce fisiere sa se uite:

var path = require('path');

module.exports = {
	entry: './assets/js/index.js',
	output: {
		filename: 'bundle.js',
		path: path.resolve(__dirname, 'dist')
	},
	// Aici adaugam JSHint loader
	module: {
		rules: [{
			test: /\.js$/, // vrem sa rulam loader-ul pe toate fisierele .js
			exclude: /node_modules/, // vrem sa ignoram toate fisierele din folder-ul node_modules
			use: 'jshint-loader'
		}]
	}
};

Acum, daca rulam npm run build o sa o lista de warning-uri (pe care le vom ignora pentru moment):

Acum, codul nostru va merge astfel:

Concluzii

Ne vom opri aici cu acest tutorial, oricum tutorialul acesta este deja prea mare. Dar, daca vreti sa aflati mai multe despre webpack am sa va las o lista de recomandari cu resurse ce va vor ajuta.

-   webpack.js.org
-   Awesome webpack
-   Webpack 2 - A full tutorial
Webpack Examples

Programator de ~8 ani, am lucrat la proiecte din mai multe industrstrii, de la eCommerce la telecomunicatii la automatizari. In acest timp am folosi diferite tehnologii, de la PHP, MySQL, PostgreSql, RabbitMq, Redis, Memcached si altele.


Get in touch
Pentru nelamuriri, dubii, comentarii si chestii de pe suflet ne putem auzi pe Discord, Reddit sau poti deschide o discutie noua pe forum

Avodart vs. Dutasteride for hair loss # 5 months ago magnificent publish, very informative. I'm wondering why the opposite experts of this sector do not understand this. You should proceed your writing. I am confident, you have a great readers' base already!
Coping with Anxiety and Stress during Divorce # 5 months ago Hi there, after reading this remarkable piece of writing i am as well delighted to share my know-how here with colleagues.
https://maps.google.com.ua/url?sa=t&url=https://www.hkflowersdelivery.com # 5 months ago |Wear darker blouses and pants if you want to appear slimmer. Dark colors help emphasize your good parts and tone down the overweight extras you don't want people to notice. You should wear skirts with elastic waistbands if you are concerned about comfort.
louboutin heels cheap # 3 months ago |One thing you are going to want to do is always keep an eye open for changes in style. Styles are constantly changing, and you can find out what is new by looking at fashion magazines every now and then. They are likely going to showcase the new trends first.
https://maps.google.com.mt/url?q=https://www.topoakleysoutlet.com/ # 3 months ago |Wearing white after the end of summer used to be considered a huge fashion faux pas. Any color, as long as it is flattering, is appropriate. So, if it's white you want to wear, wear it proudly and ignore people who say you shouldn't. Most people don't even think about what time of year it is when regarding your outfit.
https://darylschuppe.blogstival.com/41788123/helpful-information-for-anyone-suff # 3 months ago |A fabulous handbag can spruce up any outfit, but match it up with other bags you may also need to carry. For example, if you carry a briefcase, coordinate your handbag with your briefcase. You should only ever have a maximum of two bags on you at the same time.
https://charley76.free-blogz.com/66628156/how-to-get-a-stronghold-on-affiliate-m # 3 months ago |White and black are always popular colors that you will want to wear. Models are sporting colorless looks at every fashion show. You can certainly fit these colors into many of your outfits. Black and white separates offer endless possibilities.
achat de somnifères vectrin # 1 month ago Awesome post.
buspar 5 mg sin receta a precio elevado # 1 month ago My brother recommended I might like this web site. He was totally right. This post truly made my day. You can not imagine simply how much time I had spent for this information! Thanks!
commander revatio en Belgique # 1 month ago Thank you for the auspicious writeup. It in fact was a amusement account it. Look advanced to more added agreeable from you! However, how can we communicate?
prix du metforbell à Marseille # 1 month ago Incredible points. Solid arguments. Keep up the amazing effort.
Candra # 1 month ago Hi, I do believe this is an excellent website. I stumbledupon it ;) I may come back yet again since i have book-marked it. Money and freedom is the best way to change, may you be rich and continue to guide others.
freiverkäuflicher ventoline in Belgien # 1 month ago What's up, I wish for to subscribe for this weblog to get newest updates, thus where can i do it please assist.
Yvette # 4 weeks ago Woah! I'm really enjoying the template/theme of this site. It's simple, yet effective. A lot of times it's very hard to get that "perfect balance" between user friendliness and appearance. I must say you've done a awesome job with this. Also, the blog loads super fast for me on Opera. Exceptional Blog!
Omar # 4 weeks ago Having read this I believed it was extremely enlightening. I appreciate you finding the time and energy to put this information together. I once again find myself personally spending a significant amount of time both reading and commenting. But so what, it was still worthwhile!
Luz # 4 weeks ago Excellent article! We will be linking to this great article on our website. Keep up the great writing.
Kathie # 4 weeks ago Aw, this was a really good post. Taking a few minutes and actual effort to generate a superb article… but what can I say… I procrastinate a whole lot and never manage to get anything done.
Rolland # 3 weeks ago I just like the helpful information you provide for your articles. I'll bookmark your weblog and take a look at again here regularly. I am fairly sure I will be told a lot of new stuff right here! Best of luck for the next!
Colleen # 3 weeks ago Highly descriptive blog, I loved that a lot. Will there be a part 2?
Dominic # 3 weeks ago I absolutely love your blog.. Very nice colors & theme. Did you create this site yourself? Please reply back as I'm attempting to create my own blog and want to find out where you got this from or just what the theme is named. Many thanks!
Keith # 2 weeks ago Somebody necessarily assist to make severely articles I might state. That is the very first time I frequented your website page and up to now? I amazed with the analysis you made to create this particular submit amazing. Wonderful process!
Dallas # 2 weeks ago Greetings! This is my first visit to your blog! We are a collection of volunteers and starting a new project in a community in the same niche. Your blog provided us beneficial information to work on. You have done a outstanding job!
zovirax 200 en vente en ligne en Suisse # 2 weeks ago Hurrah! After all I got a webpage from where I can actually take useful data regarding my study and knowledge.
online apotheek in Nederland die capegard verkoopt # 2 weeks ago Hi! I could have sworn I've been to this site before but after browsing through many of the articles I realized it's new to me. Nonetheless, I'm certainly pleased I discovered it and I'll be book-marking it and checking back frequently!
https://www.camisetasceltics.es/sitemaps.xml # 4 days ago |Don't buy something simply because of a great price. If it does not flatter you, it is actually a bad deal. You'll end up donating it and that's just flushing cash down the toilet.
Club-ul este dedicat membrilor si ofera access la mai multe zone ale website-ului.
Login Register

🔖 Bookmarks
✨ Pentru a sustine aceasta comunitate am sa te rog sa te autentifici sau sa te inregistrezi!

🌪️ Discord
Back to top
Folosim cookie-uri pentru a oferi functionalitatile critice ale aplicatiei Invata-Programare. Folosim cookie-uri si pentru a analiza traficul, pentru care e nevoie de consimtamantul dvs. explicit.