Next.js 未在nextjs中加载dotenv值

Next.js 未在nextjs中加载dotenv值,next.js,dotenv,Next.js,Dotenv,我正在努力在我的NextJS应用程序中加载我的.env文件。这是我的密码: 我的.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

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

我的
.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
module.exports = {
    'CSV_UPLOAD_URL': "http://localhost:3000/uploadcsv"
}
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
    }
})))
My 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 }
}
My
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"
  }
}
错误:

Module build failed (from ./node_modules/next/dist/build/webpack/loaders/next-babel-loader.js):
TypeError: Property property of MemberExpression expected node to be of a type ["Identifier","PrivateName"] but instead got "StringLiteral"
如果你想用

  • 安装巴别塔插件转换定义
  • 创建env-config.js文件并定义变量

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

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

     process.env.BACKEND_URL
    

  • 备选方案:

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

    一旦安装。编辑
    next.config.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
    
    module.exports = {
        'CSV_UPLOAD_URL': "http://localhost:3000/uploadcsv"
    }
    
    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
        }
    })))
    

    从Next.js 9.4开始,有一个内置的环境变量设置解决方案

    我认为您的babel配置是错误的,我制作了一个codesandbox来向您展示;)您的沙盒未能编译。我错过了什么吗?修复了,发生了一些奇怪的事情。不知道为什么,但当我尝试在gitlab ci中运行下一个构建时,这个就不起作用了。.env在那里,在本地工作,在那里…如果我尝试在next.config.js文件中输入console.log,它就是空的。有什么建议吗?