An warware: buƙatar ('dotenv').config()

Fahimtar sauye-sauyen yanayi yana da mahimmanci yayin haɓaka aikace-aikace tare da Node.js. Mutum zai iya yin mamaki, menene ainihin waɗannan canjin yanayi? Suna kawai ƙima mai ƙarfi-mai ƙarfi akan injin ku waɗanda za'a iya amfani da su don tara bayanan da aikace-aikacenku ke buƙatar amfani da su. Don sarrafa waɗannan lokacin aiki tare da Node.js, muna amfani da fakitin ɓangare na uku dotenv wanda ake amfani dashi don loda masu canji daga fayil ɗin .env zuwa cikin tsari.env.

Saita Dotenv

Mataki na farko na yin amfani da dotenv a cikin aikace-aikacen Typescript ɗinku shine shigar da kunshin kanta. Ana iya cika wannan ta hanyar gudanar da umarni mai zuwa a tushen aikin ku:

npm install dotenv

Bayan kammala shigarwar kunshin dotenv, mataki na gaba shine yin fayil ɗin .env a tushen aikace-aikacen Typescript ɗin ku. Ana amfani da wannan fayil galibi don adana mahimman bayanai kamar maɓallan API ɗinku, kalmomin sirri na bayanai, ko saitunan sanyi waɗanda ba za ku so mai hacker ya gani ba.

Yadda ake Amfani da Dotenv

Bayan ƙirƙirar fayil ɗin .env, muna buƙatar kiran hanyar daidaitawar dotenv don saita masu canjin yanayin mu. Bukatar 'dotenv' kuma kira hanyar 'config()' a saman fayil ɗin shigarwar ku.

require('dotenv').config()

Abin da ke da mahimmanci a lura a nan shi ne tsarin kiran lambar ya dace saboda da zarar an kira `dotenv.config()`, za a iya samun dama ga masu canjin yanayi ta hanyar `process.env`.

Fayil ɗin .env daga inda kunshin dotenv ke ɗauko bayanai yawanci yana da KEY=VALUE nau'i-nau'i. Yana yiwuwa a yi amfani da waɗannan maɓallan a lambar Rubutun ku ta hanyar kiran `process.env.KEY`.

Fahimtar Canjin Muhalli

A gefe guda, muna iya samun ƙima daban-daban don masu canji don mahalli daban-daban. Za mu iya samun ƙima ɗaya don yanayin 'ci gaba' da wata ƙima ta daban don yanayin 'samuwar'. Don magance wannan matsalar, zamu iya ƙara yanayin sauyawa wanda ke amfani da mabambantan yanayi daban-daban dangane da ƙimar 'NODE_ENV'.

id let config = {}

switch (process.env.NODE_ENV) {
  case 'development':
    config = process.env.DEVELOPMENT
    break
  case 'production':
    config = process.env.PRODUCTION
    break
}

Wannan yana ba mu damar sauƙaƙe da kuma kiyaye daidaito a cikin yanayi daban-daban.

A fagen ci gaban Node.js, fahimta da aiwatar da sauye-sauyen yanayi da kyau mataki ne mai mahimmanci ga kowane ƙwararru. Yin amfani da fakitin da ake buƙata kamar `dotenv` ba kawai yana haɓaka haɓakarmu a matsayin masu haɓakawa ba, har ma yana haɓaka amintaccen lamba, mai daidaitawa da kiyayewa. Fahimtar `dotenv` zai ware ku kuma ya sanya ku zama mafi kyawun mai haɓaka Node.js.

Shafi posts:

Leave a Comment