我有一个使用Webpack和Babel的React应用程序,我尝试使用 process.env 在我的react组件中加载.env
常量,但此对象始终为空。看起来后台正在运行dotenv
插件,但它无法使用我的项目。
我希望在我的反应组件中看到.env(位于应用程序的根目录)常量。
我的package.json
:
{
"name": "**************",
"version": "0.1.0",
"private": true,
"dependencies": {
"axios": "^0.16.2",
"babel-core": "^6.25.0",
"babel-loader": "^7.0.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"bootstrap": "^3.3.7",
"dotenv": "^4.0.0",
"dotenv-webpack": "^1.5.3",
"material-ui": "^0.18.3",
"react": "^15.6.1",
"react-bootstrap": "^0.31.0",
"react-dom": "^15.6.1",
"react-router": "^4.1.1",
"react-router-dom": "^4.1.1",
"react-tap-event-plugin": "^2.0.1",
"webpack": "^2.6.1"
},
"devDependencies": {
"css-loader": "^0.28.4",
"file-loader": "^0.11.2",
"react-scripts": "1.0.7",
"style-loader": "^0.18.2",
"url-loader": "^0.5.9"
},
"scripts": {
"dev": "webpack -d --watch",
"test": "react-scripts test --env=jsdom",
"start": "react-scripts start",
"build": "webpack -p",
"eject": "react-scripts eject"
}
}
我的webpack.config.js
:
var webpack = require('webpack');
var path = require('path');
var BUILD_DIR = path.resolve(__dirname, 'src/client/public');
var APP_DIR = path.resolve(__dirname, 'src/client/app');
const Dotenv = require('dotenv-webpack');
module.exports = {
entry: APP_DIR + '/index.jsx',
output: {
path: BUILD_DIR,
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.jsx?/,
include: APP_DIR,
loader: 'babel-loader'
},
{
test: /\.css$/,
loader: "style-loader!css-loader"
},
{
test: /\.png$/,
loader: "url-loader?limit=100000"
},
{
test: /\.jpg$/,
loader: "file-loader"
},
{
test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?limit=10000&mimetype=application/font-woff'
},
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?limit=10000&mimetype=application/octet-stream'
},
{
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
loader: 'file'
},
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url?limit=10000&mimetype=image/svg+xml'
}
]
},
plugins: [
new Dotenv({
path: './.env', // Path to .env file (this is the default)
safe: false // load .env.example (defaults to "false" which does not use dotenv-safe)
})
]
};
我试过以下:
DotenvPlugin - 没有工作。
DefinePlugin - 我设法使用来自webpack conf的DefinePlugin加载常量,但我确实需要能够使用.env
文件。
有什么想法吗?
答案 0 :(得分:2)
一个问题可能是默认情况下create-react-app会忽略任何没有前缀为'REACT_APP _'的.env变量
create-react-app中有一节让我Here更详细地解释了这一点
他们背后的理由是你不能无意中包含系统中其他项目的环境变量