简体   繁体   中英

How does this expression work? "require('dotenv').config();"

I saw this expression:

require('dotenv').config();

At the beginning of a server.js file within a NodeJS project. I am just curious to know how does it work and what does it do?

Because almost always I have seen a variable before the require expression line like

 const express = require('express'); 

and afterwards it will be used somehow like

const app = express();

But require('dotenv').config(); looks different and it hasn't been used like the common approach.

Import Types

When you define a type in the package.json file, it will set that import type for the whole project. require() cannot be used in type module and import cannot be used in type commonJS

Example package.json

{
  "name": "stack",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "type": /* either commonJS or module */
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

after setting the import type here are the examples of both types in action

// if "type": "commonJS"
const package = require('package')

// if "type": "module"
import package from 'package'

'dotenv'

This is the environment variables module to read .env files. Below are the two ways to import it whether you're using type commonJS or module

require('dotenv').config() // commonJS

import {} from 'dotenv/config' // module

works like this...

.env file

TOKEN=THIS_IS_MY_TOKEN

then in a .js file

/* after importing 'dotenv' one of the two ways listed above */

console.log(process.env.TOKEN) // outputs "THIS_IS_MY_TOKEN"

'express'

this is the two ways to import express with either commonJS or module

const express = require('express') // commonJS

import express from 'express' // module

const app = express() // initializes express app

CommonJS vs ES Module

ES modules are the standard for JavaScript, while CommonJS is the default in Node. js. The ES module format was created to standardize the JavaScript module system. It has become the standard format for encapsulating JavaScript code for reuse.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM