paint-brush
Kushanda neEnvironment Variables muFrontend Application Releasesby@egorgrushin

Kushanda neEnvironment Variables muFrontend Application Releases

by Egor Grushin11m2024/10/30
Read on Terminal Reader

Kurebesa; Kuverenga

Frontend zvikumbiro zvechinyakare zvinoda zvivakwa zvakaparadzana kune yega yega nharaunda (budiriro, dhizaini, kugadzirwa) nekuti nharaunda dzakasiyana dzakamisikidzwa panguva yekuvaka, zvichikonzera kuwedzera kuburitswa nguva. Ini ndinopa mhinduro yekuvaka iyo yekumberi application kamwe chete uye jekiseni nharaunda-yakatarwa machinjiro panguva yekutumirwa nekushandisa zvinobatirira nzvimbo uye script kuti zvivatsive nehunhu chaihwo panguva yekuendesa. Iyi nzira inorerutsa maitiro ekuburitsa, inoderedza nguva dzekuvaka, inovimbisa kuenderana munzvimbo dzese, uye inoderedza njodzi yezvipembenene zvine chekuita nekuvaka. Pamusoro pezvo, nekugadzirisa filename hashing mushure mekusiyana jekiseni, iyo nzira inochengetedza inoshanda browser caching uye yakazara application kuita.
featured image - Kushanda neEnvironment Variables muFrontend Application Releases
Egor Grushin HackerNoon profile picture
0-item


Mamirioni epamberi-yekupedzisira maapplication ari kutonga nharaunda-yakatarwa kuvaka. Kune yega yega nharaunda - ingave budiriro, dhizaini, kana kugadzirwa - yakaparadzana kuvaka yepamberi app inofanirwa kugadzirwa, uye iyo yakakodzera nharaunda inosiyana inofanirwa kusetwa. Huwandu hwezvivakwa hunowanda kana akawanda maapplication akabatanidzwa, zvichiwedzera kuvhiringidzika. Iri rave riri dambudziko rakajairika kwenguva yakareba, asi pane nzira iri nani yekubata nharaunda dzakasiyana. Ini ndawana nzira yekukwenenzvera iyi maitiro, uye mune ino chinyorwa, ini ndinokutungamira nhanho-ne-nhanho kuti ugadzire nzira inoshanda iyo inoderedza nguva dzekuvaka uye kukubatsira iwe kuve nechokwadi chekuenderana munzvimbo dzese mumapurojekiti ako.


Kunzwisisa mamiriro akasiyana

Tisati tatanga, ndinofunga tinofanira kuita kudzokorora. Zvishandiso zveWebhu zvinogara zvichitsamira pane zvinosiyana zvinozivikanwa se "evironment variables ", izvo zvinowanzo sanganisira mukati mehurongwa hwekupedzisira, masisitimu ekubatanidza, makiyi ehurongwa hwekubhadhara, nhamba dzekuburitsa, zvichingodaro. Nomuzvarirwo, kukosha kweizvi zvinosiyana zvinosiyana zvichienderana nenharaunda iyo application inoiswa.


Semuenzaniso, fungidzira chikumbiro chinopindirana negedhi rekubhadhara. Munzvimbo yekusimudzira, iyo yekubhadhara gedhi URL inogona kunongedza kubhokisi rejecha rekuyedza (https://sandbox.paymentgateway.com), iri munzvimbo yekugadzira, inonongedza kune yehupenyu sevhisi (https://live.paymentgateway.com ) Saizvozvo, makiyi eAPI akasiyana kana chero imwe nharaunda yakatarwa kusetwa inoshandiswa kune yega yega nharaunda kuve nechokwadi chekuchengetedza data uye kudzivirira kusanganisa nharaunda.


Matambudziko ari pamberi pekuvandudzwa

Paunenge uchivaka backend application , iyi haisi nyaya. Kuzivisa izvi zvakasiyana-siyana mukodhi yekushandisa zvakakwana sezvo hutsika hwezvinhu izvi zvakachengetwa munzvimbo yevhavha iyo iyo backend inoshandiswa. Nenzira iyi, iyo backend application inovawana pakutanga.


Nekudaro, ne frontend applications zvinhu zvinowedzera kuoma. Sezvo ivo vachimhanyisa mubrowser yemushandisi, ivo havana mukana weiyo chaiyo nharaunda inosiyana kukosha. Kugadzirisa izvi, kukosha kweaya akasiyana anowanzo "kubikwa mukati" kumberi kwekushandisa panguva yekuvaka. Nenzira iyi, kana iyo application ichimhanya mubrowser yemushandisi, ese anodiwa maitiro akatoiswa mukati meiyo yekumberi application.


Iyi nzira, sevamwe vazhinji, inouya necaveat: iwe unofanirwa kugadzira yakaparadzana yekuvaka imwechete yekumberi application kune yega yega nharaunda kuitira kuti imwe neimwe kuvaka ive neyayo hunhu.


Semuenzaniso , ngatiti tine nharaunda nhatu:

  • kuvandudzwa kwekuedzwa kwemukati;

  • danho rekuedzwa kwekubatanidza;

  • uye kugadzirwa kwevatengi.


Kuti uendese basa rako kuti riyedzerwe, iwe unovaka iyo app uye woiendesa kunzvimbo yekusimudzira. Mushure mekuyedzwa kwemukati kwapera, iwe unofanirwa kuvaka iyo app zvakare kuti uiise pachikuva, uye wozoivaka zvakare kuti iendeswe kukugadzira. Kana iyo purojekiti iine anopfuura kumberi-yekupedzisira application, nhamba yekuvaka kwakadaro inowedzera zvakanyanya. Uyezve, pakati pezvivakwa izvi, iyo codebase haisi kuchinja - yechipiri neyechitatu inovaka yakavakirwa pane imwechete sosi kodhi.


Zvese izvi zvinoita kuti nzira yekuburitsa iwande, inonoke, uye inodhura, pamwe nekuunza njodzi yehutano. Pamwe chivakwa chakayedzwa zvakanaka munzvimbo yekusimudzira, asi nhanho yekuvaka inyowani, zvichireva kuti pane mukana mutsva wekukanganisa.


Muenzaniso: Une maapplication maviri ane nguva dzekuvaka dzeX uye Y masekonzi. Kune idzo nharaunda nhatu, ese maapplication aizotora 3X + 3Y munguva yekuvaka. Nekudaro, kana iwe ukagona kuvaka yega yega app kamwe chete uye kushandisa iyo yakafanana kuvaka munzvimbo dzese, iyo yakazara nguva yaizoderedzwa kusvika X + Y masekonzi chete, ichicheka nguva yekuvaka katatu.

Izvi zvinogona kuita mutsauko mukuru mumapaipi ekumberi, uko zviwanikwa zvishoma uye nguva dzekuvaka dzinogona kubva pamaminetsi mashoma kusvika kweawa. Nyaya iripo munenge mune yese frontend application pasi rose, uye kazhinji hapana nzira yekuigadzirisa. Asi, iri idambudziko rakakura, kunyanya kubva pakuona kwebhizinesi.

Hazvingave zvakanaka here kana pachinzvimbo chekugadzira matatu akapatsanurwa anovaka, iwe unogona kungogadzira imwe uye woitumira munzvimbo dzese? Zvakanaka, ndawana nzira yekuita nayo chaizvo.


Kukwenenzvera kumberi kwekutumira. Bhuku rekushandisa

Kugadzira mamiriro ekunze


  1. Kutanga, iwe unofanirwa kugadzira faira mune yako yepamberi purojekiti repository uko inodiwa nharaunda inosiyana ichanyorwa. Izvi zvichashandiswa nemugadziri munharaunda. Kazhinji, faira iyi inodaidzwa kunzi .env.local , iyo yakawanda yemazuva ano emberi mafaera anogona kuverenga. Heino muenzaniso wefaira rakadaro:


     CLIENT_ID='frontend-development' API_URL=/api/v1' PUBLIC_URL='/' COMMIT_SHA=''


    Ongorora: masisitimu akasiyana anoda akasiyana mazita makongiresi ezvakasiyana nharaunda. Semuyenzaniso, muReact, unofanira kufanogadzirira REACT_APP_ kumazita akasiyana. Iri faira haridi kuti ribatanidze mavhezheni anobata application zvakananga; inogona zvakare kuve nerubatsiro rwekugadzirisa ruzivo. Ini ndakawedzera iyo COMMIT_SHA shanduko, yatichazodhonza kubva pabasa rekuvaka kuti titevere kuzvipira uku kwakavakirwa.


  2. Zvadaro, gadzira faira inonzi environment.js , kwaunogona kutsanangura kuti ndeapi mabhii emamiriro ezvinhu aunoda. Iyo yekumberi framework ichakuisira izvi. For React, semuenzaniso, iwo akachengetwa mu process.env chinhu:


     const ORIGIN_ENVIRONMENTS = window.ORIGIN_ENVIRONMENTS = { CLIENT_ID: process.env.CLIENT_ID, API_URL: process.env.API_URL, PUBLIC_URL: process.env.PUBLIC_URL, COMMIT_SHA: process.env.COMMIT_SHA }; export const ENVIRONMENT = { clientId: ORIGIN_ENVIRONMENTS.CLIENT_ID, apiUrl: ORIGIN_ENVIRONMENTS.API_URL, publicUrl: ORIGIN_ENVIRONMENTS.PUBLIC_URL ?? "/", commitSha: ORIGIN_ENVIRONMENTS.COMMIT_SHA, };


  1. Pano, unotora zvese zvakatanga kukosha zvezvakasiyana window.ORIGIN_ENVIRONMENTS chinhu, chinokutendera kuti uzvione mubrowser's console. Uyezve, iwe unofanirwa kuakopa mune ENVIRONMENT chinhu, kwaunogona zvakare kuseta zvimwe zvisizvo, semuenzaniso: isu tinofungidzira publicUrl ndeye / nekukasira. Shandisa ENVIRONMENT chinhu pese panodiwa mavhezheni aya mukushandisa.


    Panguva ino, wazadzisa zvese zvinodiwa zvebudiriro yenzvimbo. Asi chinangwa ndechekubata nharaunda dzakasiyana.


  2. Kuti uite izvi, gadzira .env faira rine zvinotevera zvirimo:

 CLIENT_ID='<client_id>' API_URL='<api_url>' PUBLIC_URL='<public_url>' COMMIT_SHA=$COMMIT_SHA

Mune faira iri, iwe uchada kudoma zvibatiso zvezvakasiyana zvinoenderana nenharaunda. Vanogona kuve chero chaunoda, chero bedzi vakasiyana uye vasingapindire neyako kodhi kodhi neimwe nzira. Kuti uwedzere kuvimbiswa, unogona kushandisa kunyange UUIDs - Universal Unique Identifiers.


Kune izvo zvinosiyana izvo zvisingasanduke munzvimbo dzese (semuenzaniso, iyo hashi yekuzvipira), unogona kunyora iwo chaiwo maitiro zvakananga kana kushandisa hunhu huchave huripo panguva yekuvaka basa (senge $COMMIT_SHA ). Iyo yekumberi sisitimu inotsiva aya anobatisa nzvimbo nemakoshero chaiwo panguva yekuvaka maitiro:


File
File

  1. Iye zvino iwe unowana mukana wekuisa mune chaiwo hunhu pachinzvimbo chezvibatiso. Kuti uite izvi, gadzira faira, inject.py (ndakasarudza Python, asi unogona kushandisa chero chishandiso kune ichi chinangwa), icho chinofanira kutanga chine mepu yezvibatiso kumazita akasiyana:


 replacement_map = { "<client_id>": "CLIENT_ID", "<api_url>": "API_URL", "<public_url>": "PUBLIC_URL", "%3Cpublic_url%3E": "PUBLIC_URL" }

Ziva kuti public_url yakanyorwa kaviri, uye chechipiri chatiza mabhuraketi. Iwe unoda izvi kune ese akasiyana anoshandiswa muCSS uye HTML mafaera.


  1. Zvino ngatiwedzerei runyoro rwemafaira atinoda kugadzirisa (uyu ungave muenzaniso weNginx):


 base_path = 'usr/share/nginx/html' target_files = [ f'{base_path}/static/js/main.*.js', f'{base_path}/static/js/chunk.*.js', f'{base_path}/static/css/main.*.css', f'{base_path}/static/css/chunk.*.css', f'{base_path}/index.html' ]


  1. Zvadaro, isu tinogadzira iyo injector.py faira, kwatinogashira mepu uye runyorwa rwekuvaka artifact mafaera (akadai seJS, HTML, uye CSS mafaera) uye kutsiva vanobata nzvimbo nehunhu hwezvakasiyana kubva kwatinogara.


 import os import glob def inject_envs(filename, replacement_map): with open(filename) as r: lines = r.read() for key, value in replacement_map.items(): lines = lines.replace(key, os.environ.get(value) or '') with open(filename, "w") as w: w.write(lines) def inject(target_files, replacement_map, base_path): for target_file in target_files: for filename in glob.glob(target_file.glob): inject_envs(filename, replacement_map)


Uyezve, mune inject.py faira, wedzera iyi mutsara (usakanganwa kuendesa kunze injector.py ):

 injector.inject(target_files, replacement_map, base_path)


  1. Iye zvino tinofanira kuva nechokwadi chokuti inject.py script inongoshanda panguva yekuendesa chete.Unogona kuiwedzera Dockerfile mumutemo CMD mushure mekuisa Python uye kukopa zvose zvinyorwa:
 RUN apk add python3 COPY nginx/default.conf /etc/nginx/conf.d/default.conf COPY --from=build /app/ci /ci COPY --from=build /app/build /usr/share/nginx/html CMD ["/bin/sh", "-c", "python3 ./ci/inject.py && nginx -g 'daemon off;'"]That's it! This way, during each deployment, the pre-built files will be used, with variables specific to the deployment environment injected into them.


Ndizvo! Nenzira iyi, panguva yekutumirwa kwega kwega, mafaera ekutanga-akavakwa achashandiswa, aine akasiyana akanangana nenzvimbo yekutumirwa akaiswa mavari.


Faira: File


Kubata filename hashing kune yakakodzera browser caching

Chinhu chimwe - kana zvivakwa zvako zvekuvaka zvinosanganisira hashi yemukati mumafaira avo, jekiseni iri harizokanganisa mazita emafaira uye izvi zvinogona kukonzera matambudziko nebrowser caching. Kuti ugadzirise izvi, mushure mekugadzirisa mafaera ane majekiseni akasiyana, unozofanirwa:


  1. Gadzira hashi nyowani yemafaira akagadziridzwa.
  2. Isa iyi hashi nyowani kumazita emafaira, saka bhurawuza inoatora semafaira matsva.
  3. Gadziridza chero mareferensi kumazita ekare efaira mukodhi yako (senge zvirevo zvekutumira) kuti aenderane nemazita efaira matsva.


Kuti uite izvi, wedzera hashi raibhurari import ( import hashlib ) uye anotevera mabasa kune inject.py faira.


 def sha256sum(filename): h = hashlib.sha256() b = bytearray(128 * 1024) mv = memoryview(b) with open(filename, 'rb', buffering=0) as f: while n := f.readinto(mv): h.update(mv[:n]) return h.hexdigest() def replace_filename_imports(filename, new_filename, base_path): allowed_extensions = ('.html', '.js', '.css') for path, dirc, files in os.walk(base_path): for name in files: current_filename = os.path.join(path, name) if current_filename.endswith(allowed_extensions): with open(current_filename) as f: s = f.read() s = s.replace(filename, new_filename) with open(current_filename, "w") as f: f.write(s) def rename_file(fullfilename): dirname = os.path.dirname(fullfilename) filename, ext = os.path.splitext(os.path.basename(fullfilename)) digest = sha256sum(fullfilename) new_filename = f'{filename}.{digest[:8]}' new_fullfilename = f'{dirname}/{new_filename}{ext}' os.rename(fullfilename, new_fullfilename) return filename, new_filename


Asi, haasi mafaera ese anoda kupihwa zita. Semuyenzaniso, iyo index.html filename inofanirwa kuramba isina kuchinjika uye kuti uite izvi, gadzira TargetFile kirasi inochengeta mureza unoratidza kana kutumidza zita zvichidikanwa:


 class TargetFile: def __init__(self, glob, should_be_renamed = True): self.glob = glob self.should_be_renamed = should_be_renamed


Iye zvino iwe unongofanirwa kutsiva hurongwa hwemafaira mu inject.py nehurongwa TargetFile kirasi zvinhu:

 target_files = [ injector.TargetFile(f'{base_path}/static/js/main.*.js'), injector.TargetFile(f'{base_path}/static/js/chunk.*.js'), injector.TargetFile(f'{base_path}/static/css/main.*.css'), injector.TargetFile(f'{base_path}/static/css/chunk.*.css'), injector.TargetFile(f'{base_path}/index.html', False) ]


Uye gadziridza inject basa injector.py kuti ubatanidze kutumidza zita refaira kana mureza waiswa:


 def inject(target_files, replacement_map, base_path): for target_file in target_files: for filename in glob.glob(target_file.glob): inject_envs(filename, replacement_map) if target_file.should_be_renamed: filename, new_filename = rename_file(filename) replace_filename_imports(filename, new_filename, base_path)


Nekuda kweizvozvo, iyo artifact mafaera achatevera iyi yekupa zita: <origin-file-name> . <injection-hash> . <extension> .


Zita refaira risati rabaya jekiseni:

Zita refaira risati rabaya jekiseni


Zita refaira mushure mejekiseni:Zita refaira mushure mejekiseni


Mamiriro ezvinhu akafanana anoburitsa zita rimwechete refaira, zvichibvumira bhurawuza yemushandisi kuti ichengetedze faira nemazvo. Ikozvino kune vimbiso yekuti iwo chaiwo hunhu hwemhando idzi huchachengetwa mubrowser cache, semhedzisiro - kuita zvirinani kumutengi.


Mhinduro yekufambiswa kwemaitiro akakwenenzverwa

Maitiro echinyakare ekugadzira akasiyana anovaka ega ega nharaunda akatungamira kune mashoma akakosha kusashanda, izvo zvinogona kuve nyaya kuzvikwata zvine zviwanikwa zvishoma.


Iwe zvino une purani yemaitiro ekuburitsa anogona kugadzirisa nguva refu yekutumirwa, yakawandisa kuvaka, uye yakawedzera njodzi mukusimbisa kwemhando yezvikumbiro zvemberi - zvese. Zvese panguva yekuunza nhanho nyowani yeyakavimbiswa kuenderana munzvimbo dzese.


Panzvimbo pekuda N kuvaka, iwe unongoda imwe chete. Pakuburitswa kuri kuuya, unogona kungoendesa chivakwa chakange chaedzwa kare, icho chinobatsirawo kugadzirisa zvingangoitika zvebug nekuti iyo yakafanana kuvaka ichashandiswa munzvimbo dzese. Uyezve, kumhanya kwekuita kwechinyorwa ichi kwakakurumidza zvisingaenzaniswi kupfuura kunyange yakanyanya kugadziridzwa kuvaka. Semuenzaniso, mabhenji emunharaunda paMacBook 14 PRO, M1, 32GB ndeaya anotevera:


Maitiro angu anorerutsa maitiro ekuburitsa, anochengetedza mashandiro ekushandisa nekubvumira nzira dzinoshanda dzecaching, uye inova nechokwadi chekuti mabug ane chekuita nekuvaka haapinde munzvimbo. Uyezve, iyo nguva yese uye simba rakamboshandiswa pamabasa anonetesa ekuvaka zvino anogona kutariswa mukugadzira yakatonyanya nani mushandisi ruzivo. Chii chisiri chekuda?


Isu tinoona kuti mabugs ane chekuita nekuvaka haatsvedze muapp kune dzimwe nharaunda. Panogona kunge paine phantom bugs inoratidzira nekuda kwekusakwana mumasisitimu ekuvaka. Mikana midiki, asi iripo.