【问题标题】:dotenv values not loaded in nextjsnextjs 中未加载 dotenv 值
【发布时间】:2019-05-02 05:16:01
【问题描述】:

我正在努力将我的 .env 文件加载到我的 NextJS 应用程序中。这是我的代码:

我的.env 在根目录/
我的index.js/pages/index.js

这是我的index.js

require("dotenv").config({ path: __dirname + '/../.env' })

import React, {Component} from 'react'
import Layout from '../components/layout'
import axios from 'axios'

class Import extends Component{

    uploadCSV = (evt) => {
        evt.preventDefault();

        const uploadURL = process.env.MY_UPLOAD_URL

        let data = new FormData(evt.target)

        axios.post(uploadURL, data, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        }).then((res) => {
            console.log(res)
        })
    }

    render() {
        return (
            <div>
                <Layout title="Import Chatbot Intents" description="Import Chatbot Intents">
                    <form onSubmit={this.uploadCSV} name="import_csv" className="import_csv">
                        <h2>Import CSV</h2>
                        <div className="form-group">
                            <label htmlFor="csv_file">Upload file here: </label>
                            <input type="file" name="csv_file" id="csv_file" ref="csv_file" />
                        </div>
                        <div className="form-group">
                            <input type="hidden" id="customer_id" name="customer_id" ref="customer_id" value="1"/>
                            <button className="btn btn-success">Submit</button>
                        </div>
                    </form>
                </Layout>
            </div>
        )
    }
}

export default Import

我观察到我可以在render() 函数中打印出.env 内容,但我不能在uploadCSV 函数中这样做。

供您参考:

  • 仅使用 require("dotenv").config() 不起作用
  • 使用require("dotenv").config({path: "../"}) 不起作用

更新

我的env-config.js

module.exports = {
    'CSV_UPLOAD_URL': "http://localhost:3000/uploadcsv"
}

我的 babel.config.js:

const env = require('./env-config')
console.log(env)

module.exports = function(api){

  // console.log({"process": process.env})
  api.cache(false)

  const presets = [
    "next/babel",
    "@zeit/next-typescript/babel"
  ]

  const plugins = [

      "@babel/plugin-transform-runtime",
      [
        'transform-define',
        env
      ]
  ]

  return { presets, plugins }
}

我的package.json

{
  "name": "Botadmin",
  "scripts": {
    "dev": "next -p 3001",
    "build": "next build",
    "start": "next start"
  },
  "dependencies": {
    "@babel/runtime": "^7.1.5",
    "@zeit/next-less": "^1.0.1",
    "@zeit/next-typescript": "^1.1.1",
    "@zeit/next-workers": "^1.0.0",
    "axios": "^0.18.0",
    "forever": "^0.15.3",
    "less": "^3.8.1",
    "multer": "^1.4.1",
    "next": "7.0.2",
    "nprogress": "^0.2.0",
    "papaparse": "^4.6.2",
    "react": "16.6.3",
    "react-dom": "16.6.3",
    "typescript": "^3.1.6",
    "worker-loader": "^2.0.0"
  },
  "devDependencies": {
    "@babel/plugin-transform-runtime": "^7.1.0",
    "babel-plugin-transform-define": "^1.3.0",
    "dotenv": "^6.1.0",
    "fork-ts-checker-webpack-plugin": "^0.4.15"
  }
}

错误:

模块构建失败(来自 ./node_modules/next/dist/build/webpack/loaders/next-babel-loader.js):

TypeError:MemberExpression 预期节点的属性属性为 ["Identifier","PrivateName"] 类型,但得到的是 "StringLiteral"

【问题讨论】:

    标签: next.js dotenv


    【解决方案1】:

    我知道我来晚了,但是,您可以安装 dotenv 并在您的 next.config.js 文件中使用它

    require("dotenv").config();
    
    const environment = process.env.NODE_ENV || "dev";
    

    【讨论】:

      【解决方案2】:

      从 Next.js 9.4 开始,有一个用于设置环境变量的内置解决方案https://nextjs.org/docs/basic-features/environment-variables

      【讨论】:

      • 买家注意 next.js 环境仅支持通过next dev 和“生产”进行“开发”。除了使用 next.js 环境进行生产构建之外,您无法执行任何其他操作 - 您可能在 Vercel 云中拥有更大的灵活性,但您必须为此付费。
      【解决方案3】:

      感谢@Alex 的回答。解决相同问题的另一种方法是使用npm install -D dotenv-webpack 安装dotenv-webpack

      安装后。编辑next.config.js:

      require('dotenv').config()
      const Dotenv = require('dotenv-webpack')
      
      const path = require('path')
      
      const withTypescript = require('@zeit/next-typescript')
      const withWorkers = require('@zeit/next-workers')
      const withLess = require('@zeit/next-less')
      
      module.exports = withWorkers(withLess(withTypescript({
          context: __dirname,
          generateEtags: false,
          entry: './pages/index.js',
          distDir: 'build',
          pageExtensions: ['js', 'jsx', 'ts', 'tsx'],
      
          cssModules: false,
      
          webpack: (config, options) => {
      
              config.plugins = config.plugins || []
      
              config.plugins = [
                  ...config.plugins,
      
                  // Read the .env file
                  new Dotenv({
                      path: path.join(__dirname, '.env'),
                      systemvars: true
                  })
              ]
      
              // Fixes npm packages that depend on `fs` module
              config.node = {
                  fs: 'empty'
              }
      
              return config
          }
      })))
      

      【讨论】:

      • 不知道为什么,但是例如,当我尝试在 gitlab ci 中运行下一个构建时,这个就不起作用了。 .env 在那里,它在本地工作并且在那里......如果我尝试 console.log in next.config.js 文件,它只是空的。有什么建议吗?
      【解决方案4】:

      如果你想使用env in Nextjs

      1. 安装babel-plugin-transform-define
      2. 创建 env-config.js 文件并定义变量

        const prod = process.env.NODE_ENV === 'production'
        module.exports = {
         'process.env.BACKEND_URL': prod ? 'https://api.example.com' : 'https://localhost:8080'
        }
        
      3. 创建 .babelrc.js 文件

        const env = require('./env-config.js')
        
        module.exports = {
         presets: ['next/babel'],
         plugins: [['transform-define', env]] 
        }
        
      4. 现在您可以访问代码中的环境

         process.env.BACKEND_URL
        

      替代方案:next-env

      【讨论】:

      • 我觉得你的 babel 配置有问题,我做了一个codeandbox给你看;)codesandbox.io/s/jl560l17ww
      • 您的沙箱编译失败。我错过了什么吗?
      • 已修复,发生了一些奇怪的事情。
      猜你喜欢
      • 2017-07-06
      • 1970-01-01
      • 2018-06-05
      • 2022-07-03
      • 1970-01-01
      • 2020-10-07
      • 1970-01-01
      • 2017-07-09
      • 1970-01-01
      相关资源
      最近更新 更多