1. // npm install dotenv
    2. // 之所以要使用 dotenv ,就是为了避免在代码中写死一些数据,比如项目的端口号,环境变量等
    3. // 在项目的根目录下面新建一个 .env 文件,书写 APP_POST=3002,这是项目启动的端口号
    4. // 在项目src目录下面新建 config/config.default.js 文件,注意,后续如果需要配置dev环境变量,可以新增
    5. // config/config.dev.js
    6. const dotenv = require('dotenv')
    7. // 读取.env文件,写入到 process.env 中
    8. dotenv.config()
    9. console.log('process', process.env.APP_PORT) // 这样就可以获取到之前设置在 .env 文件中的 APP_PORT 的值
    10. // 导出,供其它模块使用
    11. module.exports = process.env
    1. // main.js 中使用
    2. const app = require('./app')
    3. const { APP_PORT } = require('./config/config.default')
    4. app.listen(APP_PORT, () => {
    5. console.log('server is running')
    6. })