Reputation: 81
I have a React app working with Webpack and Babel, I'm trying to load the .env
constants in my react components using process.env but this object is always empty. It looks like there is dotenv
plugin running in the background, but it's not working with my project.
I expect to see the .env(located at the root of the app) constants inside my react components.
My 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"
}
}
My 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)
})
]
};
I tried following:
Adding Development Environment Variables In .env — didn't work.
DotenvPlugin — didn't work.
DefinePlugin — I managed to load constants using DefinePlugin from webpack conf but I really need to be able to use .env
files instead.
Any ideas?
Upvotes: 2
Views: 2537
Reputation: 213
One issue may be that create-react-app by default will ignore any .env variables that aren't prefixed with 'REACT_APP_'
There is a section in the create-react-app read me Here that explains this in more detail
Their reasoning behind it is so you can't unintentionally include environment variables from other projects on your system
Upvotes: 3