我从头开始构建了一个React应用程序(即:不使用create-react-app),并且一直在尝试从根目录中的.env文件中检索环境变量。我尝试了几种使用Webpack做到这一点的方法-包括Dotenv和webpack.DefinePlugins-尽管软件包dotenv-webpack似乎是最合适的。每种方法都导致相同的错误:
ContactForm.js:112 Uncaught ReferenceError: process is not defined
at ContactForm.email (ContactForm.js:112)
at ContactForm.handleSubmit (ContactForm.js:100)
at HTMLUnknownElement.callCallback (react-dom.development.js:149)
at Object.invokeGuardedCallbackDev (react-dom.development.js:199)
at invokeGuardedCallback (react-dom.development.js:256)
at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:270)
at executeDispatch (react-dom.development.js:561)
at executeDispatchesInOrder (react-dom.development.js:583)
at executeDispatchesAndRelease (react-dom.development.js:680)
at executeDispatchesAndReleaseTopLevel (react-dom.development.js:688)
这是我的webpack.config文件:
const HtmlWebpackPlugin = require('html-webpack-plugin');
const Dotenv = require('dotenv-webpack');
const path = require('path');
module.exports = {
entry: './src/index.js',
mode: 'development',
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
options: {presets: ['@babel/env']},
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
],
},
resolve: {extensions: ['*', '.js', '.jsx']},
output: {
path: path.resolve(__dirname, 'seabirdviewer/'),
publicPath: '/seabirdviewer/',
filename: 'bundle.js',
},
devServer: {
contentBase: path.join(__dirname, 'public/'),
port: 3000,
publicPath: 'http://localhost:3000/seabirdviewer/',
hotOnly: true,
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve('./public/index.html'),
}),
new Dotenv({
path: './.env',
safe: true,
}),
],
externals: [
(context, request, callback) => {
if (/pe-wasm$/.test(request)) {
return callback(null, 'amd ' + request);
}
callback();
},
],
node: {
process: false,
global: false,
},
};
和引发错误的组件:
// External imports
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import emailjs from 'emailjs-com';
// Local imports
import FormInput from '../GlobalElements/FormInput';
/**
* This class displays a form to contact a team member in the browser
*/
class ContactForm extends Component {
/**
* **************************** Setup ****************************************
*/
static propTypes = {
recipientEmail: PropTypes.string.isRequired,
recipientName: PropTypes.string.isRequired,
};
state = {
senderEmail: '',
senderName: '',
emailContent: '',
attemptedSubmit: false,
emailSent: false,
};
/**
* ************************* Event handlers **********************************
* Sync state with user input
* @param {event} e
*/
handleChange(e) {
const {name, value} = e.target;
this.setState({
[name]: value,
});
}
/**
* On submit, check that user info is valid. If so,
* email and save
* @param {event} e
*/
handleSubmit(e) {
e.preventDefault();
const {senderEmail, senderName, emailContent} = this.state;
this.setState({
attemptedSubmit: true,
});
if (senderEmail && senderName && emailContent) {
this.email();
// TODO: Save to database
}
}
/**
* ************************* Helper methods **********************************
* Send email via Email JS
*/
email() {
const userID = process.env.EMAIL_JS_USERID;
const templateID = process.env.EMAIL_JS_TEMPLATEID_CONTACT;
const {senderEmail, senderName, emailContent} = this.state;
const {recipientEmail, recipientName} = this.props;
emailjs.init(userID);
emailjs.send(
'mailgun',
templateID,
{
website_name: 'Seabirds',
sender_name: senderName,
sender_email: senderEmail,
recipient_name: recipientName,
recipient_email: recipientEmail,
email_content: emailContent,
})
.then(() => {
this.setState({
emailSent: true,
});
console.log('success');
})
.catch((err) => {
console.error('Failed to send feedback. Error: ', err);
});
}
/**
* *********************** Visual component **********************************
* @return {jsx}
*/
render() {
return (
<form onSubmit={this.handleSubmit.bind(this)}>
{/* User Email */}
<FormInput label="Your Email"
type="email"
placeholder="you@email.com"
name="senderEmail"
required={true}
rows={1}
handleChange={this.handleChange.bind(this)} />
{/* User Name */}
<FormInput label="Your Name"
type="text"
placeholder="Jane Doe"
name="senderName"
required={true}
rows={1}
handleChange={this.handleChange.bind(this)} />
{/* Email Body */}
<FormInput label="Email Content"
placeholder="Write your email here"
name="emailContent"
required={true}
rows={10}
handleChange={this.handleChange.bind(this)}/>
{/* Submit button */}
<button type="submit">Submit</button>
</form>
);
}
}
export default ContactForm;
我正在使用npm start
运行应用程序,该程序在我的package.json中指定为webpack-dev-server --mode development