我正在努力将我的.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
我观察到我可以在函数中打印出.env
内容render()
,但我不能在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"