brunch / brunch

:fork_and_knife: Web applications made easy. Since 2011.
https://brunch.io
MIT License
6.8k stars 433 forks source link

dotenv & Brunch: environment variables in code #1806

Closed tarciozemel closed 4 years ago

tarciozemel commented 6 years ago

Description

The essence of this issue is understand how to use env variables in code with Brunch.

More specificaly, in "overrides" section of config docs we found:

It is also possible to set an additional environment value using the BRUNCH_ENV or NODE_ENV environment variable. This can be especially useful when combined with dotenv.

So I installed dotenv, create some variables in a .env file in the root of the project and try to:

import dotenv from 'dotenv'
dotenv.config()

console.log(process.env.TEST_KEY)

But the thing didn't goes very well...

Expected behavior

The expected behavior is something like the Create React App wepack environment variables autoimport: I put some vars in .env file and voilà!

Environment

  1. Brunch: 2
  2. Node.js: 9.8.0
  3. NPM: 5.7.1
  4. Operating system: Ubuntu 16.04.4 LTS (Linux ubuntu-pc 4.13.0-38-generic x86_64)
  5. Code editor: Visual Studio Code

package.json contents

{
  "name": "recursos-frontend",
  "description": "Recursos front-end web site",
  "private": true,
  "author": "w!",
  "version": "1.0.0",
  "repository": "",
  "scripts": {
    "start": "brunch watch --server",
    "build": "brunch build --production"
  },
  "dependencies": {
    "preact": "8.1.0"
  },
  "devDependencies": {
    "auto-reload-brunch": "2",
    "babel-brunch": "6.0",
    "babel-plugin-transform-react-jsx": "6.24.1",
    "babel-preset-latest": "6",
    "brunch": "2",
    "clean-css-brunch": "2",
    "dotenv": "5.0.1",
    "sass-brunch": "2.10.4",
    "uglify-js-brunch": "2"
  }
}

brunch config contents

exports.files = {
  javascripts: {
    joinTo: {
      'vendor.js': /^(?!app)/,
      'script.js': /^app/
    }
  },
  stylesheets: {joinTo: 'style.css'}
}

exports.plugins = {
  babel: {
    presets: ['latest'],
    plugins: [
      ['transform-react-jsx', {pragma: 'h'}]
    ]
  }
}

exports.watcher = {
  awaitWriteFinish: true,
  usePolling: true
}
tjomk commented 5 years ago

Any update on this?

tarciozemel commented 5 years ago

Brunch is very good, but his community is dead...

reubano commented 4 years ago

Works for me.

Brunch: 3 Node.js: 12.6.1 NPM: 6.14.x

brunch-config.js

require('dotenv').config()

console.log(process.env.TEST_KEY)
...
$ npm start

> App@1.1.1 start /Users/reubano/Documents/Projects/app
> brunch watch --server

test_value
...
reubano commented 4 years ago

The key to getting dotenv to work in files other than brunch-config.js is process-env-brunch.

.env

TEST_KEY=fizz

app/config.js

console.log($PROCESS_ENV_TEST_KEY);

module.exports = {
  ...
}