【发布时间】:2019-02-26 23:44:02
【问题描述】:
我的 React 应用不是使用“create-react-app”构建的。
我能够从 webpack.config.js 控制台记录我使用 dotenv 库从 .env 文件导入和解析的进程环境。
但是,“npm run build”失败。当我用 URL 字符串替换变量时,'npm run build' 通过。
webpack.config.js
const webpack = require('webpack');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const dotenv = require('dotenv').config({path: 'config/docker/production/.env'});
// call dotenv and it will return an Object with a parsed key
const env = dotenv.parsed;
// reduce it to a nice object, the same as before
const envKeys = Object.keys(env).reduce((prev, next) => {
prev[`process.env.${next}`] = JSON.stringify(env[next]);
return prev;
}, {});
console.log(process.env.API_URL); -> prints out http://localhost:5000/api/something
const config = {
entry: __dirname + '/static/js/index.jsx',
output: {
path: __dirname + '/static/dist',
filename: 'bundle.js',
},
resolve: {
extensions: [".js", ".jsx", ".css"]
},
module: {
rules: [
{
test: /\.jsx?/,
exclude: /node_modules/,
use: 'babel-loader'
},
{
test: /\.css$/,
use: ['style-loader', MiniCssExtractPlugin.loader, 'css-loader']
},
{
test: /\.(png|svg|jpg|gif)$/,
use: 'file-loader'
}
]
},
plugins: [
new MiniCssExtractPlugin({
path: __dirname + '/static/dist',
filename: 'styles.css',
}),
new webpack.DefinePlugin(envKeys)
]
};
module.exports = config;
package.json
"scripts": {
"build": "webpack --mode production -p --progress --config webpack.config.js"
}
config/docker/production/.env
API_URL=http://]ocalhost:5000/api/something
MyComp.jsx
import React,{ Component } from 'react';
class MyComp extends Component {
constructor(props) {
super(props);
this.state = {
races: []};
}
componentDidMount(){
fetch({process.env.API_URL}) -> FAILS
fetch('http://localhost:5000/api/something') -> PASSES
.then(results => results.json())
.then(data => this.setState({ races: data.data }));
}
render() {
...
}
}
export default MyComp;
【问题讨论】:
标签: node.js reactjs webpack environment-variables