【问题标题】:.env with next.js on local.env 和 next.js 在本地
【发布时间】:2020-03-27 04:34:59
【问题描述】:

我有两个关于.env的文件

.env.local

STAGE=local
API=http://localhost:3333

.env.dev

STAGE=dev
API=https://dev.api.domain.com

我想把它们分开为package.json的脚本

我想要什么

"script": {
    "start-local": ".env.local && next",
    "start-dev": ".env.dev && next"
}

【问题讨论】:

    标签: environment-variables next.js


    【解决方案1】:

    您可以通过某个环境变量加载特定的.env 文件。

    例如:

    "script": {
        "start-local": "NODE_ENV=local next",
        "start-dev": "NODE_ENV=dev next"
    }
    

    这将定义NODE_ENV 环境变量,然后基于它,您可以使用dotenv lib 加载正确的文件。

    // next.config.js
    const dotEnv = require('dotenv');
    const path = require('path');
    
    const envFilePath = path.join(__dirname, `.env.${process.env.NODE_ENV}`); // this will have the path to the proper `.env` file
    
    dotEnv.config({ path: envFilePath }); 
    
    module.exports = {
      ...
    } 
    

    【讨论】:

      猜你喜欢
      • 2020-03-25
      • 2022-08-19
      • 2015-07-07
      • 2022-01-05
      • 1970-01-01
      • 2019-10-18
      • 1970-01-01
      • 2020-05-25
      • 2022-06-21
      相关资源
      最近更新 更多