I'm trying to access my .env file variables using dotenv-webpack so that they can be bundled later and I can use them on my website, however I followed the instructions and have looked online and can't make it work.
//.env
VAR=1234
// created a webpack.config.js with the following code
const Dotenv = require('dotenv-webpack');
module.exports = {
plugins: [
new Dotenv()
]
};
// index.js
console.log(process.env.VAR);
// undefined
I'm not sure what to do because I've followed the example in: https://github.com/mrsteele/dotenv-webpack and it seems like it should be easy...
CodePudding user response:
Why you don't use dotenv package?
CodePudding user response:
As suggested by Pandhu Wibowo, please give him the thumbs up, I managed to make it work using webpack-cli, webpack and dotenv packages. How to pass .env file variables to webpack config?
./env
VAR=1234
./webpack.config.js
const webpack = require('webpack');
// replace accordingly './.env' with the path of your .env file
require('dotenv').config({ path: './.env' });
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
},
plugins: [
new webpack.DefinePlugin({
"process.env": JSON.stringify(process.env)
}),
]
};
./package.json
"scripts": {
"start": "webpack"
},
npm run start
--> creates the bundle.js which will include the env variable
