dotenv-webpack icon indicating copy to clipboard operation
dotenv-webpack copied to clipboard

Failed to load ./.env.

Open elissaioskon opened this issue 8 years ago • 22 comments

Hello,

When webpack build is runing it prints Failed to load ./.env. dotenv-webpack version : ^1.5.5 I do server side rendering with react and my webpack for server is

const path = require('path');
const webpackNodeExternals = require('webpack-node-externals');
const webpack = require('webpack');
const Dotenv = require('dotenv-webpack');

const webpackConfig = {


    target: 'node',
    node: {
        __dirname: false,
        __filename: false,
    },

    devtool: 'sourcemap',

    entry: path.resolve(__dirname, '../../src/server/express.js'),

    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, '../../src/server/build')
    },

 

    externals: [webpackNodeExternals()],
    module: {
        rules: [
            {
                test: /(\.js|\.jsx)?$/,
                loader: 'babel-loader',

              

                exclude: /node_modules/,
                options: {
                    presets: [
                        'react',
                        'stage-0',
                        'env',
                    ],
                   
                    plugins: ['transform-runtime', 'transform-class-properties', "transform-react-jsx"]
                }
            },
            {
                test: /\.css$/,
                use: [
                    {
                        loader: 'isomorphic-style-loader',
                    },
                    {
                        loader: 'css-loader',
                        options: {
                            modules: true,
                            importLoaders: 1,
                            localIdentName: '[name]__[local]___[hash:base64:5]',

                        }
                    }
                ]

            },
            {
              
                test: /\.(png|jpg|svg)$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: '[name].[ext]',
                            outputPath: '/public/images',
                            publicPath: '/images',
                            emitFile: false
                        }
                    }
                ]
            }
        ]
    },

    resolve: {
        extensions: ['.js', '.jsx']
    },
    plugins: [
     
        new Dotenv({
            path: './.env'
        }),
        new webpack.BannerPlugin({
            banner: 'require("source-map-support").install();',
            raw: true, entryOnly: false
        }),
        new webpack.DefinePlugin({
            'process.env.ENVIRONMENT': JSON.stringify('ENVIRONMENT')
        })
    ]
};

module.exports = webpackConfig

I cannot figure out why this is happening. .env file is in the same folder as webpack config. i also tried path: '.env' but nothing

elissaioskon avatar May 13 '18 14:05 elissaioskon

Is there a place I can view your file structure? It must be running webpack itself from another directory...

mrsteele avatar May 14 '18 12:05 mrsteele

I'm experiencing something similar!

On package.json:

    "webpack": "^4.8.1",
    "dotenv-webpack": "^1.5.5",

My webpack config:

const Dotenv = require('dotenv-webpack');

  ...

  plugins: [
    new HtmlWebpackPlugin({
      template: `${ __dirname }/../src/index.html`,
      filename: 'index.html',
      inject: 'body',
    }),

    new Dotenv({
      path: '../.env/development',
      safe: false,
      silent: false,
    }),
  ],

  ...

The File Structure:

<rootDir>
│
├── package.json
│
├──  .webpack/
│       ├── development.config.js
│       └── production.config.js
│
├──  .env/
│       ├── development
│       └── production
│
├── src/
├── dist/
├── assets/
├── README.md
├── storybooks/
└── tests/

When I run webpack or webpack-dev-server, they show the message:

Failed to load ../.env/development.

Webpack still builds my project, but when I try to console.log( process.env.NODE_ENV ), for instance, I get undefined.

Any idea? Maybe this is related with Webpack 4+ version?

System Info Ubuntu 17.10 Node v8.9.4 NPM 6.0.0

brunogsa avatar May 14 '18 13:05 brunogsa

Here is my folder structure: image

I have 2 webpacks one for browzer bundleand one for expressjs bundle. The fail to read .env happens all the time, regardless if i run one one webpack or both or cliecnt webpack or server webpack

elissaioskon avatar May 14 '18 17:05 elissaioskon

I believe it depends on where you RUN webpack.

i.e. if you run it via your project root (which is the current assumption of the plugin), it uses /path/to/project/root/.env. If you run webpack from a nested directory, it will most likely use that.

It does not matter where your webpack.config.js file is as webpack may run from one directory and load a configuration from another.

If you want to use your webpack.config.js file as your reference point, might I suggest you do the following:

const path = require('path')
const Dotenv = require('dotenv-webpack')

// ... pretend you had all that other stuff in here...

Dotenv({
  path: path.resolve(__dirname, './.env')
})

Using __dirname will allow you to resolve based on the current files directory, and then use the .env that is in the same directory as your webpack file.

Let me know if that solves everything.

mrsteele avatar May 16 '18 18:05 mrsteele

I am still running into issues even when using the path.reslove(__dirname, './.env') approach.

kashi-halma avatar May 16 '18 23:05 kashi-halma

Might I direct you to https://github.com/mrsteele/dotenv-webpack-example

This uses webpack 4+, and it shows a basic usage example of how this plugin successfully loads the env.

I just updated all dependencies to make sure it all works and its working with the latest webpack as expected. Since everything is still working I don't think this is a bug with the plugin but more of a misconfigured env issue.

I believe the path.resolve approach would solve for everyone above aside from @bleudreams. I'm not sure what your directories look like or the rest of your config or node/npm versions are so I wouldn't be able to help until you give me a little more information.

mrsteele avatar May 17 '18 14:05 mrsteele

Greetings @mrsteele, thank you so much for your quick response.

Right now I am using webpack version "4.8.3" and all of my dependencies are pretty up to date. Despite using the path.resolve approach, I am still running into issues.

In a developmental setting, this dotenv webpack plugin works beautifully. But, when I deploy to heroku I am running into the "failed to load" issues.

Attached is an image that paints a picture of my current file structure, maybe this could give you more insight as to what is precipitating my issue. If you need more info, please tell me.

Again, thank you.

KRH screen shot 2018-05-17 at 8 27 56 am

kashi-halma avatar May 17 '18 14:05 kashi-halma

@bleudreams I just made another update to the example repo. See how I am using path.resolve? I also tested putting it into the src folder to make sure its working as expected.

There must be something happening outside of the context of this directory. The only thing I could think of off the top of my mind is that you are building the webpack.config.js file and putting that into another directiry, and because of that you lose the actual context of the .env file that currently exists inside the scope of this file.

One things to try is maybe put the output of path.resolve(__dirname) into a console.log to make sure your build sequence doesn't move that config file somewhere else.

mrsteele avatar May 17 '18 16:05 mrsteele

sorry for the late response,my problem that i had wrote at the beginning solved with path: path.resolve(__dirname, './.env')

elissaioskon avatar May 26 '18 21:05 elissaioskon

Thanks for the update @elissaioskon, I think this will solve it at least 75% of the time, and the other 25% of the time you got what I suggested here: https://github.com/mrsteele/dotenv-webpack/issues/121#issuecomment-389928258

mrsteele avatar May 27 '18 02:05 mrsteele

My solution, maybe help: const Dotenv = require('dotenv-webpack'); const { definitions } = new Dotenv(); plugins: [ new webpack.DefinePlugin({ ...definitions }), ] if i add Dotenv directly to plugins, i receive empty object. "dotenv-webpack": "^1.5.7", "webpack": "^4.15.1",

dimon85 avatar Aug 29 '18 12:08 dimon85

@dimon85 That is the approach I took to resolve this problem before, however what you will see is that it exposes ALL of your env variables to the bundle.

# .env
TEST=hi
SECRET=NO!
// main.js
console.log(process.env.TEST)
// bundle.js (currently)
console.log('hi')
// bundle.js (your approach)
console.log({"TEST": "hi", "SECRET": "NO!"}.TEST)

As you can see from the above, the approach suggested leaves all variables exposed. While this option is viable, it is also to be used with caution.

mrsteele avatar Aug 29 '18 14:08 mrsteele

I got it work in Webpack 4.20.2 using:

plugins: [
    new Dotenv({
        path: path.resolve(__dirname, '..', '.env'),
    }),
]

when my file structure is

<project>
|_ .env
|_webpack/
    |_webpack.common.js

One gotcha I found is that Dotenv sets these variables as individual properties named process.env.VARIABLE, rather than a single process.env property with an object with separate members for each variable.

I noticed this while trying examining definitions from the const { definitions } = new Dotenv() approach in https://github.com/mrsteele/dotenv-webpack/issues/121#issuecomment-416933066

The upshot is that trying to do console.log(process.env) gave me an empty object (which made me think I was not getting any variables), but later I found that directly using console.log(process.env.VARIABLE) gave me any value I wanted.

That makes sense, given this library only exposes the variables you use directly.

edelreal avatar Oct 29 '18 14:10 edelreal

@edelreal

One gotcha I found is that Dotenv sets these variables as individual properties named process.env.VARIABLE, rather than a single process.env property with an object with separate members for each variable.

Thank you

I was getting an empty object 💃

DannyFeliz avatar Dec 01 '18 14:12 DannyFeliz

Hello, this plugin works locally but not when I push to Heroku? Can someone please point out what I might be doing wrong? Env vars are undefined in Heroku for some reason. Thank you.

webpack.config:

const path = require('path');
const Dotenv = require('dotenv-webpack');

module.exports = {
  context: path.join(__dirname, '/src'),

  entry: {
    javascript: './js/index'
  },

  output: {
    filename: 'bundle.js',
    path: path.join(__dirname, '/dist'),
  },

  resolve: {
    alias: {
      react: path.join(__dirname, 'node_modules', 'react')
    },
    extensions: ['.js', '.jsx'],
  },

  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loaders: ['babel-loader'],
      },
      {
        test: /\.html$/,
        loader: 'file?name=[name].[ext]',
      },
    ],
  },
  plugins: [
    new Dotenv({
      path: path.resolve(__dirname,'.env')
    }),
  ]
};

Files: screen shot 2019-01-18 at 1 36 47 pm

sWarren35 avatar Jan 18 '19 21:01 sWarren35

You .env file is not uploaded to Heroku. Please use Heroku's console to define the environment variables. Go to Settings tab, under Config Vars.

johncpang avatar Feb 01 '19 19:02 johncpang

For heroku deploy @sWarren35 .

I set "systemvars" as TRUE and all good.

Heroku finally can use my ENV vars. I guess this should help

valeriosillari avatar Apr 28 '19 17:04 valeriosillari

I'm having the same issue. If I check for definitions, the variables, are there. However, if I try and access a variable, contained within my .env file, it's undefined. Here is my setup. I should point out, I have a base config for webpack, and a prod version of webpack which imports the base and merges it. I've also ensured that my .env and .env-example contain all variables, with .env only have definitions for each variable. I also want to point out, I wanted to get a variable with a path, from my .env file, in order to configure output.path. Depending on the project location, this will always change. Am I not able to access .env variables, within a webpack file?

webpack.config.js

const
  path = require("path"),
  webpack = require('webpack'),
  Dotenv = require('dotenv-webpack'),
  { CleanWebpackPlugin } = require('clean-webpack-plugin'),
  WebpackMd5Hash = require("webpack-md5-hash"),
  OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin'),
  TerserJSPlugin = require('terser-webpack-plugin');

module.exports = {
  entry: path.join(__dirname, "src", "index.js"), 
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      },
      {
        test: /\.(jpg|jpeg|png|gif|svg)$/,
        loader: 'image-webpack-loader',
        // Specify enforce: 'pre' to apply the loader
        // before url-loader/svg-url-loader
        // and not duplicate it in rules with them
        enforce: 'pre'
      },
      {
        test: /\.svg$/,
        loader: 'svg-url-loader',
        options: {
          // Images larger than 10 KB won’t be inlined
          limit: 10 * 1024,
          // Remove quotes around the encoded URL –
          // they’re rarely useful
          noquotes: true,
        }
      },
      {
        test: /\.(jpg|jpeg|png|gif)$/i,
        use: [{
          loader: 'url-loader',
          options: {
            limit: 10 * 1024,
            //fallback: 'responsive-loader', //<--- At some point, I may have to configure this.  
            quality: 85
          }
        }]
      },
      {
        test: /\.(mp3)$/,
        use: [
          {
            loader: "file-loader",
            options: {
              //name: "[path][name]-[hash:8].[ext]"
              name: "[path][name].[ext]"
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new webpack.NoEmitOnErrorsPlugin(),//Base    
     new Dotenv({
       safe: true
    }),//Base,
    new WebpackMd5Hash()
  ],//Base
  externals: {
    "react": "React",
    "react-dom": "ReactDOM",
    'prop-types': "PropTypes",
    "jquery": "jQuery",
    'popper.js': {
      root: 'PopperJS',
      commonjs2: 'popper.js',
      commonjs: 'popper.js',
      amd: 'popper.js',
    },
    bootstrap: "bootstrap"
  },//Base
  optimization: {
    minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
    runtimeChunk: 'single',
    splitChunks: {
      chunks: 'all',
      maxInitialRequests: Infinity,
      minSize: 0,
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name(module) {
            // get the name. E.g. node_modules/packageName/not/this/part.js
            // or node_modules/packageName
            const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];

            // npm package names are URL-safe, but some servers don't like @ symbols
            return `${packageName.replace('@', '').replace('.js', '')}`;
          },
        },
      }
    }
  },
};

webpack.prod.js

const
    path = require("path"),
    appRoot = require('app-root-path'),
    HtmlWebpackPlugin = require('html-webpack-plugin'),
    MiniCssExtractPlugin = require("mini-css-extract-plugin"),
    merge = require("webpack-merge"),
    baseConfig = require("./webpack.base"),
    root = appRoot.path.toLocaleLowerCase().replace("frontend", "");
    //dotenv =  new Dotenv();
    //{ definitions } = dotenv;

    const { PROD_BUILD_PATH } = process.env
    console.log(`eeeee PROD_BUILD_PATH: ${PROD_BUILD_PATH}`);
module.exports = (env, argv) => {

    const
        outPutPath = argv.PROD_BUILD_PATH || env.PROD_BUILD_PATH || process.env.PROD_BUILD_PATH,
        //Build an output path for the css files. But put them in the content folder
        outPutPathCss = argv.outPutPathCss || env.outPutPathCss;

    console.log(`outPutPath: ${root}${outPutPath || "moo"}`); //<-- PUT THIS in the declaration for output path with an ||

    // console.log(`typeof process ${typeof process}`);
    // console.log(`typeof process.env ${typeof process.env}`);
    // console.log(`typeof env ${typeof env}`);
    // console.log(`typeof process.env.PROD_BUILD_PATH ${typeof process.env.PROD_BUILD_PATH}`); //<---undefined
    // console.log(`typeof env.PROD_BUILD_PATH ${typeof env.PROD_BUILD_PATH}`); //<---undefined

    const { PROD_BUILD_PATH } = process.env
    //console.log(`Welll PROD_BUILD_PATH: ${JSON.stringify( process.env)}`);  //<---undefined
    return merge(baseConfig, {
        output: {
            path: path.resolve(`${root}${outPutPath}`, 'Common/'), //<--This should be the root only
            filename: "scripts/[contenthash].js",
            publicPath: "/Common/"
        },
        module: {
            rules: [
                {
                    test: /\.(css|scss)$/,
                    use: [
                        MiniCssExtractPlugin.loader,
                        //"style-loader", //<--don't uncomment this one
                        "css-loader",
                        "postcss-loader",
                        "sass-loader"
                    ]
                }
            ]
        },
        plugins: [
            new HtmlWebpackPlugin({
                inject: "body",
                template: `${root}HtmlWebpackPluginTest/HtmlWebpackPluginTest/Views/Shared/_LayoutTemplate.cshtml`,
                filename: `${root}HtmlWebpackPluginTest/HtmlWebpackPluginTest/Views/Shared/_Layout.cshtml`,
                reactUrl: "https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js", //Lets us load the appropriate dev scripts in the html
                reactDomUrl: "https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js", //Lets us load the appropriate dev scripts in the html
                reactPropTypes: "https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.7.2/prop-types.min.js",
                bootstrap: "https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js",
                bootStrapCss: "https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css",
                jQuery: "https://code.jquery.com/jquery-3.4.1.slim.min.js",
                popperjs: "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.15.0/umd/popper.min.js"
            }),
            new MiniCssExtractPlugin({
                filename: "css/[name].[contenthash].css",  //Does this need to be split up between prod and dev
                chunkFilename: "[id].[contenthash].css"
            })
        ]
    });
};     

.env

CLIENT_API_URL=localhost:3500
HTTPONLY=false
PROXY_API_URL=http://localhost:8123
PORT=6700
PROD_BUILD_PATH=HtmlWebpackPluginTest/HtmlWebpackPluginTest/

.env.example

CLIENT_API_URL
HTTPONLY
PROXY_API_URL
PORT=6700
PROD_BUILD_PATH

I have tried putting the dotenv-weback configuration in both the config and the production files. Not at the same time. And in both cases they are undefined. I've also removed returning a function, and just an object, from the production file. Still undefined. This is perplexing. My .env and .env-example files are in the root, along with the webpack files.

TerrySlack avatar Jul 06 '19 17:07 TerrySlack

Unfortunately destructing doesn’t work. It’s a limitation with webpack.DefinePlugin.

Try to reference it outright.

mrsteele avatar Jul 06 '19 18:07 mrsteele

Yes, you are right @mrsteele. However, am I not able to access the variables through process.env, or env if I were to use a method to return my merged webpack files? At this point, I'm using an env.js file and with destructuring, pulling out what I need. Accessing the variables in the rest of the program works. But I'm not able to access them in either of the webpack files I've posted.

TerrySlack avatar Jul 06 '19 21:07 TerrySlack