简体   繁体   English

这个表达式是如何工作的? “需要('dotenv').config();”

[英]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.在 NodeJS 项目中server.js文件的开头。 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因为我几乎总是在require表达式行之前看到一个变量,例如

 const express = require('express'); 

and afterwards it will be used somehow like然后它会以某种方式被使用

const app = express();

But require('dotenv').config();但是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.当您在 package.json 文件中定义type时,它将为整个项目设置该导入类型。 require() cannot be used in type module and import cannot be used in type commonJS require()不能用于module类型, import不能用于commonJS类型

Example package.json示例 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' 'dotenv'

This is the environment variables module to read .env files.这是读取.env文件的环境变量模块。 Below are the two ways to import it whether you're using type commonJS or module以下是导入它的两种方法,无论您使用的是commonJS类型还是module

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

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

works like this...像这样工作...

.env file .env文件

TOKEN=THIS_IS_MY_TOKEN

then in a .js file然后在.js文件中

/* 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这是使用commonJSmodule导入 express 的两种方法

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

import express from 'express' // module

const app = express() // initializes express app

CommonJS vs ES Module CommonJS 与 ES 模块

ES modules are the standard for JavaScript, while CommonJS is the default in Node. ES 模块是 JavaScript 的标准,而 CommonJS 是 Node.js 中的默认模块。 js. js。 The ES module format was created to standardize the JavaScript module system.创建 ES 模块格式是为了标准化 JavaScript 模块系统。 It has become the standard format for encapsulating JavaScript code for reuse.它已成为封装 JavaScript 代码以供重用的标准格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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