Coder Social home page Coder Social logo

mrsteele / dotenv-webpack Goto Github PK

View Code? Open in Web Editor NEW
1.3K 8.0 74.0 1.28 MB

A secure webpack plugin that supports dotenv and other environment variables and only exposes what you choose and use.

License: MIT License

JavaScript 100.00%
webpack-plugin dotenv-webpack dotenv webpack plugin secure environment-variables

dotenv-webpack's Introduction

dotenv webpack dotenv-webpack

A secure webpack plugin that supports dotenv and other environment variables and only exposes what you choose and use.

Installation

Include the package locally in your repository.

npm install dotenv-webpack --save-dev

Description

dotenv-webpack wraps dotenv and Webpack.DefinePlugin. As such, it does a text replace in the resulting bundle for any instances of process.env.

Your .env files can include sensitive information. Because of this,dotenv-webpack will only expose environment variables that are explicitly referenced in your code to your final bundle.

Interested in taking your environments to the next level? Check out the Dotenv Organization.

Usage

The plugin can be installed with little-to-no configuration needed. Once installed, you can access the variables within your code using process.env as you would with dotenv.

The example bellow shows a standard use-case.

Create a .env file

// .env
DB_HOST=127.0.0.1
DB_PASS=foobar
S3_API=mysecretkey

Add it to your Webpack config file

// webpack.config.js
const Dotenv = require('dotenv-webpack');

module.exports = {
  ...
  plugins: [
    new Dotenv()
  ]
  ...
};

Use in your code

// file1.js
console.log(process.env.DB_HOST);
// '127.0.0.1'

Resulting bundle

// bundle.js
console.log('127.0.0.1');

Note: the .env values for DB_PASS and S3_API are NOT present in our bundle, as they were never referenced (as process.env.[VAR_NAME]) in the code.

How Secure?

By allowing you to define exactly where you are loading environment variables from and bundling only variables in your project that are explicitly referenced in your code, you can be sure that only what you need is included and you do not accidentally leak anything sensitive.

Recommended

Add .env to your .gitignore file

Limitations

Due to the fact that we use webpack.DefinePlugin under the hood, we cannot support destructing as that breaks how this plugin is meant to be used. Because of this, please reference your variables without destructing. For more information about this, please review the issue here.

process.env stubbing / replacing

process.env is not polyfilled in Webpack 5+, leading to errors in environments where process is null (browsers).

We automatically replace any remaining process.envs in these environments with "MISSING_ENV_VAR" to avoid these errors.

When the prefix option is set, process.envs will not be stubbed.

If you are running into issues where you or another package you use interfaces with process.env, it might be best to set ignoreStub: true and make sure you always reference variables that exist within your code (See this issue for more information).

Properties

Use the following properties to configure your instance.

  • path ('./.env') - The path to your environment variables. This same path applies to the .env.example and .env.defaults files. Read more here.
  • safe (false) - If true, load '.env.example' to verify the '.env' variables are all set. Can also be a string to a different file.
  • allowEmptyValues (false) - Whether to allow empty strings in safe mode. If false, will throw an error if any env variables are empty (but only if safe mode is enabled).
  • systemvars (false) - Set to true if you would rather load all system variables as well (useful for CI purposes).
  • silent (false) - If true, all warnings will be suppressed.
  • expand (false) - Allows your variables to be "expanded" for reusability within your .env file.
  • defaults (false) - Adds support for dotenv-defaults. If set to true, uses ./.env.defaults. If a string, uses that location for a defaults file. Read more at npm.
  • ignoreStub (false) - Override the automatic check whether to stub process.env. Read more here.
  • prefix ('process.env.') - The prefix to use before the name of your env variables.

The following example shows how to set any/all arguments.

module.exports = {
  ...
  plugins: [
    new Dotenv({
      path: './some.other.env', // load this now instead of the ones in '.env'
      safe: true, // load '.env.example' to verify the '.env' variables are all set. Can also be a string to a different file.
      allowEmptyValues: true, // allow empty variables (e.g. `FOO=`) (treat it as empty string, rather than missing)
      systemvars: true, // load all the predefined 'process.env' variables which will trump anything local per dotenv specs.
      silent: true, // hide any errors
      defaults: false, // load '.env.defaults' as the default values if empty.
      prefix: 'import.meta.env.' // reference your env variables as 'import.meta.env.ENV_VAR'.
    })
  ]
  ...
};

About path settings

As previously mentioned, it is possible to customize the path where the .env file is located as well as its filename from the plugin settings:

module.exports = {
  ...
  plugins: [
    new Dotenv({
      path: './some.other.env',
    })
  ]
  ...
};

It is important to mention that this same path and filename will be used for the location of the .env.example and .env.defaults files if they are configured, this will only add the .example and .defaults suffixes respectively:

module.exports = {
  ...
  plugins: [
    new Dotenv({
      path: '../../path/to/other.env',
      safe: true, // load '../../path/to/other.env.example'
      defaults: true, // load '../../path/to/other.env.defaults'
    })
  ]
  ...
};

This is especially useful when working with Monorepos where the same configuration can be shared within all sub-packages of the repository:

.
├── packages/
│   ├── app/
│   │   └── webpack.config.js # { path: '../../.env' }
│   └── libs/
│       └── webpack.config.js # { path: '../../.env' }
├── .env
├── .env.example
└── .env.defaults

LICENSE

MIT

dotenv-webpack's People

Contributors

ahabhgk avatar alekseyleshko avatar andersdjohnson avatar beeequeue avatar chromeq avatar dannegm avatar danny-andrews-snap avatar dependabot-preview[bot] avatar dependabot[bot] avatar glifchits avatar greenkeeper[bot] avatar iansu avatar jaycanuck avatar lucasbento avatar mkrause avatar mrsteele avatar neemski avatar pauldtong avatar sajadtorkamani avatar sapegin avatar thesycamore avatar timkelty avatar tobias-trozowski avatar vuode avatar wheredoesyourmindgo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dotenv-webpack's Issues

Broken version 1.4.3

C:\Users\HP\CodeHell\test>gulp
module.js:471
    throw err;
    ^

Error: Cannot find module './src'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:\Users\HP\CodeHell\test\node_modules\dotenv-webpack\index.js:9:14)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)

Version 1.4.3 installed using npm i dotenv-webpack --save gave the above error. Tried 1.4.2 and didnt have any issue with that.

Compile errors

There are compile errors on the initial build. Resolve ASAP.

Does not work with webpack-dev-server

Hi,

it seems that dotenv-webpack does not work with webpack-dev-server. In my normal builds without webpack-dev-server I can see that the env variables are replaced as expected. But when I use webpack-dev-server all my env variables are undefined.

webpack: 3.5.5
webpack-dev-server: 2.7.1
dotenv-webpack: 1.5.4

Allow empty env vars

Getting this error: Error: Missing environment variable: CDN_HOST

webpack.config.js

...
  new DotenvPlugin({
    safe: false,
    systemvars: false
  })
...

.env

CDN_HOST=
OTHER_KEY1=ABC123

I know that I can just delete that empty key to make it work, but I'd rather dotenv-webpack just dump the vars in without any validation.

Verbose - Add the ability to log when a variable gets used

I want to provide confidence to users about the effectiveness of the plugin to provide a secure approach to use .env files with bundles.

I was thinking it may be a good idea to apply a debug parameter to output in the console during the bundle process to show when a variable gets used. This would allow users to see exactly when something gets used.

Another use case would be for shared server and client files. We could show them when a variable gets added to the bundle to allow them to see if they accidentally leaked sensitive information.

Thoughts would be greatly appreciated.

Error when a env var is not created using systemvars

Hello, I realized that if I have not set a environment variable in my system and in my webpack config I setup dotenv-webpack to get systemvars, and use this variable in my JavaScript the rendering goes crazy, it simply put the whole env without parsing anything.

Webpack 3.0 support

We should check for support in webpack 3.0.

Not to mention trying to figure out how we can be backwards compatible and future-compatible and stop greenkeeper from yelling at me.

PRs failing because lcov-file missing

For some reason the PRs are failing because the lcov file (apparently) doesn't exist.

Must be something with the build cycle somewhere but need to check it out to have more confidence accepting PRs.

Not working with webpack.DefinePlugin

Hey there!

The plugin is not working with webpack.DefinePlugin, dotenv-webpack was listed after it and was not loading any environment vars.

I tried a few things (also systemvars which does not seem to get the vars from DefinePlugin) what worked was putting dotenv-webpack call before webpack.DefinePlugin.

webpack.DefinePlugin is needed so webpack does not need to do any checks for the NODE_ENV environment and reduces the bundle size (a lot).

I guess there should be a way to get the DefinePlugin vars on dotenv-webpack.

Additional README information

I tried this library recently while trying to load some environment variables into a React + Webpack application.
There is no documentation on this, but the plugin is essentially a wrapper for dotenv and Webpack's DefinePlugin, which does a text replace on all instances of process.env in the resulting bundle.
On the client side, this means that all process.env.NODE_ENV === 'production' checks that React does get rewritten to {SECRETS}.NODE_ENV. This leaks secrets to the client side.

On the server side, this breaks code modifying process.env because all process.env calls are rewritten to {SECRETS}.

I can open a PR to update the README if you would like.

How to use it for laravel project

Hi.
I try to use it for laravel.
But I have an error.

I follow this page.
https://www.npmjs.com/package/dotenv-webpack

then i create my javascript file.
Then i try to use this file for webpage.
But this following error produced.

test.js:1 Uncaught ReferenceError: process is not defined
    at test.js:1

template page is here.

<!doctype html>
<html lang="{{ app()->getLocale() }}">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

    </head>
    <body>
        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script type="text/javascript" src="/js/test.js"></script>
    </body>
</html>

test.js is here.

console.log(process.env.APP_NAME);

.env is here.

APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:rGmcJGCh3qamzPdjhgZpO+maa1cAhRTvM0dhDgvvMC8=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
SESSION_LIFETIME=120
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null

webpack.config.js is here.


/**
 * As our first step, we'll pull in the user's webpack.mix.js
 * file. Based on what the user requests in that file,
 * a generic config object will be constructed for us.
 */

//require('../src/index');
//require(Mix.paths.mix());
const Dotenv = require('dotenv-webpack');
/**
 * Just in case the user needs to hook into this point
 * in the build process, we'll make an announcement.
 */

//Mix.dispatch('init', Mix);

/**
 * Now that we know which build tasks are required by the
 * user, we can dynamically create a configuration object
 * for Webpack. And that's all there is to it. Simple!
 */

//let WebpackConfig = require('../src/builder/WebpackConfig');

//module.exports = new WebpackConfig().build();
module.exports = {
  plugins: [
    new Dotenv({
      path: './.env', // Path to .env file (this is the default) 
      safe: true // load .env.example (defaults to "false" which does not use dotenv-safe) 
    })
  ]
};

Not able to build

When using 1.1.0, the project throws this error:

> node server.js

module.js:341
    throw err;
    ^

Error: Cannot find module './src'
    at Function.Module._resolveFilename (module.js:339:15)
    at Function.Module._load (module.js:290:25)
    at Module.require (module.js:367:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Project/node_modules/dotenv-webpack/index.js:9:14)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Module.require (module.js:367:17)```

Add an option to blacklist or whitelist some keys from .env file

I think that adding an option to omit some critical keys like passwords from our bundle is crucial to protect our application from potential security holes. Most of the times in .env files there are some critical keys like DB credentials, tokens etc so if we pass all these through DefinePlugin into our bundle things might get ugly. I propose to add at least one option to blacklist or whitelist some keys so we can do sth like:

// In webpack.config.js
new Dotenv({
    path: resolve(__dirname, '../.env'),
    systemvars: true,
    exceptions: ['DB_USER', 'DB_PASS']
}),

Support dotenv-expand?

This was brought up a while back in #80 and I wanna bring it up here.

I was doing more research about what dotenv-expand was and found that it could be a feature to simply offer the ability to expand variables using vs the regular dotenv since it appears to me that they could coexist alongside one another.

https://github.com/motdotla/dotenv-expand/blob/master/test/.env

I'm curious what other's thoughts are, especially if there are security concerns to be worried about.

Variable undefined

OS: Windows 10 Pro
dotenv-webpack: 1.4.5
webpack: 1.14.0

So I define my webpack as follows:

  plugins: [
    new Dotenv({
      path: './.env',
      safe: true
    }),
  ]

my .env as follows:

// Sentry definitions
Sentry_Key=2342342342342m24242342m2342m24
Sentry_App=23423

// Apollo project id
Apollo_ID=djty23132k23223k232323l331

and my .env.example as follows:

// Sentry definitions
Sentry_Key=
Sentry_App=

// Apollo project id
Apollo_ID=

If I call console.log(process.env.Sentry_Key) and console.log(process.env.Sentry_App), the values are displayed successfully. But console.log(process.env.Apollo_ID) displays undefined.

No matter what variables I define after Sentry_Key and Sentry_App, they all display undefined. In fact I even changed the order of the variables around, and still only Sentry_Key and Sentry_App are displayed successfully.

What is the issue here?

Need support Boolean in .env file

If you write DEBUG = false in the file, then when checking !!process.env.DEBUG //true, since the value will be read as a string ("false").

Multi-variable destructuring breaks when working with webpack 3

Hi, team,

Found an interesting bug:

Issue

Using [email protected] and [email protected],

// .env
DB_HOST=127.0.0.1
DB_PASS=foobar
S3_API=mysecretkey

Use the vars in JS:

const { DB_HOST, DB_PASS } = process.env;

Would cause runtime error:

Uncaught (in promise) ReferenceError: process is not defined

Expected

It should replace both vars at compile time.

Possible Root Cause

I believe this issue is caused by webpack/webpack#5215

So I changed the JS to:

const { DB_HOST } = process.env;
const { DB_PASS } = process.env;

It works well as expected.

I debugged the plugin and found that the underlying formatData (https://github.com/mrsteele/dotenv-webpack/blob/master/src/index.js#L63) transferred to webpack.DefinePlugin is:

{
  'process.env.DB_HOST': '"127.0.0.1"',
  'process.env.DB_PASS': '"foobar"',
  'process.env.S3_API': '"mysecretkey"'
}

However the format that recommended in webpack/webpack#5215 (comment) is:

new DefinePlugin({
  "process.env": {
    a: JSON.stringify("a"),
    b: JSON.stringify("b")
  }
})

So I guess a minor fix in dotenv-webpack would solve the issue.

However, I think it ought to be a webpack.DefinePlugin regression bug, since it the current formatData used to work well with webpack 2.

What do you think? Thanks.

Error on Webpack 2

I'm getting this useless error message:

Uncaught SyntaxError: Unexpected token : which comes from bundle.js:6470, the exact line where the environment is defined:

// bundle.js:6470

{"GRAPHQL_URL":"http://localhost:5001/graphql","PORT":"7001"}.NODE_ENV !== 'production' ? warning(element, 'ReactComponentTreeHook: Missing React element for debugID %s when ' + 'building stack', id) : void 0;

This is my webpack config:

// webpack.config.js

/* eslint-disable */

const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const dotEnv = require('dotenv-webpack');

const HOST = process.env.HOST || 'localhost';
const PORT = process.env.PORT || '7001';

module.exports = {
  context: path.resolve(__dirname, './'),
	entry: [
		`webpack-dev-server/client?http://${HOST}:${PORT}`,
		`webpack/hot/only-dev-server`,
		'./src',
	],
	// devtool: 'source-map',
	output: {
		path: path.join(__dirname, 'admin'),
		filename: 'bundle.js'
	},
	resolve: {
    modules: [
      path.join(__dirname, 'src'),
			'node_modules',
		],
    extensions: ['.js'],
	},
	module: {
    rules: [{
  		test: /\.js?$/,
      exclude: [/node_modules/],
      use: 'babel-loader',
      include: path.join(__dirname, 'src'),
  	}],
	},
	devServer: {
		contentBase: path.resolve(__dirname, 'admin'),
		noInfo: true,
		hot: true,
		inline: true,
		historyApiFallback: true,
		port: PORT,
		host: HOST,
    stats: {
      assets: true,
      colors: true,
      version: false,
      hash: false,
      timings: true,
      chunks: false,
      chunkModules: false
    },
	},
	plugins: [
		new webpack.NoEmitOnErrorsPlugin(),
		new webpack.HotModuleReplacementPlugin(),
		new HtmlWebpackPlugin({
			template: './src/index.html',
		}),
    new dotEnv({
      path: './.env',
    }),
	]
};

And this is my .env:

GRAPHQL_URL=http://localhost:5001/graphql
PORT=7001

Can you point me the way to fix it? I can also send a PR if it's a problem on the package itself.

Versions

dotenv-webpack: 1.4.0
webpack: 2.2.1
webpack-dev-server: 2.3.0

An in-range update of babel-eslint is breaking the build 🚨

Version 8.0.2 of babel-eslint was just published.

Branch Build failing 🚨
Dependency babel-eslint
Current Version 8.0.1
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

babel-eslint is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push The Travis CI build could not complete due to an error Details

Commits

The new version differs by 8 commits ahead by 8, behind by 1.

  • a0fbd50 8.0.2
  • 2004b91 require correct deps
  • fa56d21 Always use unpad (#535)
  • 295091d Allow ^ version for babel dependencies (#534)
  • d3b8519 fix(package): update babylon to version 7.0.0-beta.31 (#533)
  • 54ab4ac 8.0.1
  • c1a7882 Update README.md support (#531) [skip ci]
  • 51100c9 chore(package): update mocha to version 4.0.0 (#524)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

.env clarification

So, I've defined my Dotenv plugin as follows:

    new Dotenv({
      path: './.env', // Path to .env file (this is the default) 
      safe: true // load .env.example (defaults to "false" which does not use dotenv-safe) 
    })

and as a result need to specify both a .env and an .env.example in my root directory, the .env.example being a mirror image of .env, minus any associated values for the variables.

Why? Why can I not just specify the .env file without the need for the .env.example?

Enhance README

The readme feels lacking. Update the wording and add more content.

An in-range update of webpack is breaking the build 🚨

Version 3.1.0 of webpack just got published.

Branch Build failing 🚨
Dependency webpack
Current Version 3.0.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As webpack is “only” a devDependency of this project it might not break production or downstream projects, but “only” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this 💪

Status Details
  • continuous-integration/travis-ci/push The Travis CI build could not complete due to an error Details

Release Notes v3.1.0

Features:

  • Allow different library names for UMD
  • Support for passing a defined identifier as this in a IIFE
  • Use the new resolve performance option cacheWithContext: false by default when it's safe
  • Support array of functions as configuration
  • add sortModules to Chunk which is required in extract-text-plugin to support webpack 3

Bugfixes:

  • ! with truthy webpack identifier will evaluate correctly
  • assets and dependencies are preserved in concatenated modules
  • Fix some internal usage of deprecated APIs
Commits

The new version differs by 95 commits.

  • 4bb3018 3.1.0
  • 7e757cd Merge pull request #5194 from webpack/feature/hoist_regex_literals
  • 2879fb3 Merge pull request #5225 from hulkish/feature/added-chunk-sortModules-method
  • 5f08aa4 removed default params for node 4
  • cadf9f7 added sortModules method to Chunk class
  • 70b7d2f fix(sp): spelling mistake in const name
  • 0ab36c4 Merge pull request #5196 from AndersDJohnson/multi-compiler-functions
  • 2eccb19 Merge pull request #5081 from KTruong888/4099_es6_refactor_lib_hot_module_replacement_plugin
  • e365b2e Merge pull request #5210 from ematipico/master
  • 7913789 Merge pull request #5220 from liuyuanyangscript/master
  • 15becbd README.md bugfix
  • 2ccc1fd Changed statement 'var' to 'const'
  • a589a6c Merge pull request #5183 from kahwee/patch-1
  • c2fa5d4 feat(perf): remove unneded regexp escape
  • 987a9f3 feat(perf): hoist final regexp

There are 95 commits in total.

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

An in-range update of webpack is breaking the build 🚨

Version 2.5.1 of webpack just got published.

Branch Build failing 🚨
Dependency webpack
Current Version 2.5.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As webpack is “only” a devDependency of this project it might not break production or downstream projects, but “only” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this 💪

Status Details
  • continuous-integration/travis-ci/push The Travis CI build could not complete due to an error Details

Release Notes v2.5.1

Bugfixes:

  • Fix crash when error happens while watching
  • Fix hoisting of exports
Commits

The new version differs by 5 commits0.

  • ad2f68f 2.5.1
  • 4fd545b Merge pull request #4828 from satazor/patch-1
  • b0c45da Fix _done function not dealing with compilation being undefined
  • 7bc08e1 Merge pull request #4816 from webpack/bugfix/hoist-immutable-export
  • a952bb9 change some magic numbers to hoist exports

false

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

README.md enhancement ideas

I wanna make our README.md look flashier. Any interest in the following?

  • A logo/icon
  • Center align those badges and maybe clean them up
  • Clean up the descriptions and use cases
  • Make basic intro which just gets people ready quickly, with a longer read for people who wanna configure

Support export in .env file

Some .env files have lines like this, so that you can source the file in bash:

export S3_BUCKET=YOURS3BUCKET
export SECRET_KEY=YOURSECRETKEYGOESHERE

Here is some documentation from dotenv, which is a ruby gem: https://github.com/bkeepers/dotenv#usage

dotenv-webpack doesn't load in those env variables if it has an export in front of it. It would be nice if it supported this format.

Comparision with webpack-dotenv-plugin

I still wasn't totally clear on the function differences between this and https://github.com/nwinch/webpack-dotenv-plugin, so before using either I need to test.

My primary concern was if the entire process.env would be exposed in the bundled code.

Please correct me if I'm wrong, but it appears that:

  • your plugin will only expose process.env variables that explicitly referenced, so your secure/secret vars are not at risk of being bundled (unless you reference them)
  • https://github.com/nwinch/webpack-dotenv-plugin seems to expose all of process.env in your resulting bundle, which seems super dangerous

https://github.com/mrsteele/dotenv-webpack#how-secure
Your README does reference the fact that it is "secure" a few times, but I still had to to test to see what was going on :) I think the confusion is conflated by the face that webpack-dotenv-plugin uses dotenv-safe, which prior to investigation I assumed was a mechanism to protect secret vars, but in fact isn't that at all.

Anyway - just putting this issue here for anyone else that might go through the same thoughts.
I may send a PR to the README that might have helped me.

Yarn add issue

Hi to everyone,
I am experiencing the following warnings/error during the adding of the library to my projects during the building of the DLL. Please find more info below. The library works fine even with the error.

Warnings/errors

WARNING in ./~/chokidar/lib/fsevents-handler.js
Module not found: Error: Can't resolve 'fsevents' in '/home/daniele/repos/FAO/Follow up/ui/node_modules/chokidar/lib'
 @ ./~/chokidar/lib/fsevents-handler.js 7:17-36
 @ ./~/chokidar/index.js
 @ ./~/watchpack/lib/DirectoryWatcher.js
 @ ./~/watchpack/lib/watcherManager.js
 @ ./~/watchpack/lib/watchpack.js
 @ (webpack)/lib/node/NodeWatchFileSystem.js
 @ (webpack)/lib ^.*$
 @ (webpack)/lib/webpack.js
 @ ./~/dotenv-webpack/dist/index.js
 @ ./~/dotenv-webpack/browser.js
 @ dll FollowUpDeps

WARNING in ./~/ajv/lib/async.js
96:20-33 Critical dependency: the request of a dependency is an expression

WARNING in ./~/ajv/lib/async.js
119:15-28 Critical dependency: the request of a dependency is an expression

WARNING in ./~/uglify-js/tools/node.js
24:11-32 Critical dependency: the request of a dependency is an expression

WARNING in ./~/ajv/lib/compile/index.js
13:21-34 Critical dependency: the request of a dependency is an expression

WARNING in ./~/loader-runner/lib/loadLoader.js
3:2-28 Critical dependency: the request of a dependency is an expression

ERROR in (webpack)/lib/NormalModule.js
Module not found: Error: Can't resolve 'module' in '/home/daniele/repos/FAO/Follow up/ui/node_modules/webpack/lib'
 @ (webpack)/lib/NormalModule.js 8:21-38
 @ (webpack)/lib ^.*$
 @ (webpack)/lib/webpack.js
 @ ./~/dotenv-webpack/dist/index.js
 @ ./~/dotenv-webpack/browser.js
 @ dll FollowUpDeps

Webpack is configured based on two files:
Webpack.base.config

/**
 * COMMON WEBPACK CONFIGURATION
 */

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

module.exports = (options) => ({
    entry: options.entry,
    output: Object.assign({ // Compile into js/build.js
        path: path.resolve(process.cwd(), 'build'),
        publicPath: '/' + (process.env.PROFILE === "dev" || process.env.PROFILE === "demo"? process.env.PROFILE.toLowerCase() : "")
    }, options.output), // Merge with env dependent settings
    module: {
        rules: [
            {
                test: /\.js$/, // Transform all .js files required somewhere with Babel
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                    options: options.babelQuery,
                },
            },
            {
                // Preprocess our own .css files
                // This is the place to add your own loaders (e.g. sass/less etc.)
                // for a list of loaders, see https://webpack.js.org/loaders/#styling
                test: /\.css$/,
                exclude: /node_modules/,
                use: ['style-loader', 'css-loader'],
            },
            {
                // Preprocess 3rd party .css files located in node_modules
                test: /\.css$/,
                include: /node_modules/,
                use: ['style-loader', 'css-loader'],
            },
            {
                test: /\.(eot|svg|otf|ttf|woff|woff2)$/,
                use: 'file-loader',
            },
            {
                test: /\.(jpg|png|gif)$/,
                use: [
                    'file-loader',
                    {
                        loader: 'image-webpack-loader',
                        options: {
                            progressive: true,
                            optimizationLevel: 7,
                            interlaced: false,
                            pngquant: {
                                quality: '65-90',
                                speed: 4,
                            },
                        },
                    },
                ],
            },
            {
                test: /\.html$/,
                use: 'html-loader',
            },
            {
                test: /\.json$/,
                use: 'json-loader',
            },
            {
                test: /\.(mp4|webm)$/,
                use: {
                    loader: 'url-loader',
                    options: {
                        limit: 10000,
                    },
                },
            },
        ],
    },
    plugins: options.plugins.concat([
        new webpack.ContextReplacementPlugin(/\.\/locale$/, 'empty-module', false, /js$/),

        new webpack.ProvidePlugin({
            // make fetch available
            fetch: 'exports-loader?self.fetch!whatwg-fetch',
        }),

        // Always expose NODE_ENV to webpack, in order to use `process.env.NODE_ENV`
        // inside your code for any environment checks; UglifyJS will automatically
        // drop any unreachable code.
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: JSON.stringify(process.env.NODE_ENV),
                PROFILE: JSON.stringify(process.env.PROFILE)
            },
        }),
        new webpack.NamedModulesPlugin(),
        new Dotenv({
            path : "./.env",
            safe: false
        })
    ]),
    resolve: {
        modules: ['app', 'node_modules'],
        extensions: [
            '.js',
            '.jsx',
            '.react.js',
        ],
        mainFields: [
            'browser',
            'jsnext:main',
            'main',
        ],
    },
    devtool: options.devtool,
    target: 'web', // Make web variables accessible to webpack, e.g. window
    performance: options.performance || {},
    node: {
        fs: "empty"
    }
});

webpack.prod.config

// Important modules this config uses
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
//const OfflinePlugin = require('offline-plugin');

module.exports = require('./webpack.base.babel')({
    // In production, we skip all hot-reloading stuff
    entry: [
        path.join(process.cwd(), 'app/app.js'),
    ],

    devtool: 'source-map',

    // Utilize long-term caching by adding content hashes (not compilation hashes) to compiled assets
    output: {
        filename: '[name].[chunkhash].js',
        chunkFilename: '[name].[chunkhash].chunk.js',
    },

    plugins: [

        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor',
            children: true,
            minChunks: 2,
            async: true,
        }),

        // Minify and optimize the index.html
        new HtmlWebpackPlugin({
            template: 'app/index.html',
            minify: {
                removeComments: true,
                collapseWhitespace: true,
                removeRedundantAttributes: true,
                useShortDoctype: true,
                removeEmptyAttributes: true,
                removeStyleLinkTypeAttributes: true,
                keepClosingSlash: true,
                minifyJS: true,
                minifyCSS: true,
                minifyURLs: true,
            },
            inject: true,
        }),

        // Put it in the end to capture all the HtmlWebpackPlugin's
        // assets manipulations and do leak its manipulations to HtmlWebpackPlugin
        /* new OfflinePlugin({
         relativePaths: false,
         publicPath: '/' + (process.env.PROFILE ? process.env.PROFILE.toLowerCase() : ""),

         // No need to cache .htaccess. See http://mxs.is/googmp,
         // this is applied before any match in `caches` section
         excludes: ['.htaccess'],

         caches: {
         main: [':rest:'],

         // All chunks marked as `additional`, loaded after main section
         // and do not prevent SW to install. Change to `optional` if
         // do not want them to be preloaded at all (cached only when first loaded)
         additional: ['*.chunk.js'],
         },

         // Removes warning for about `additional` section usage
         safeToUseOptionalCaches: true,

         AppCache: false,
         }),*/
    ],

    performance: {
        assetFilter: (assetFilename) => !(/(\.map$)|(^(main\.|favicon\.))/.test(assetFilename)),
    },
});

Libs versions:

dotenv-webpack: v1.4.3
webpack: 2.4.1

Thank you very much for your support

Create unit-tests

Need to allocate some time to write this, but wouldn't mind some help ;)

Add option to watch the env file

It would be nice if Webpack automatically recompiled my application when changes are detected to my env file. Maybe a simple boolean option named watch would suffice? If possible, use chokidar, otherwise fs.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.