How to use nodemon with .env files?

后端 未结 11 935
伪装坚强ぢ
伪装坚强ぢ 2020-12-09 02:37

I am using an .env file to hold environment variables for the server. This works if I run the server with foreman start. But it doesn\'t work with nodemon.

I would

相关标签:
11条回答
  • 2020-12-09 02:54
    1. Install dotenv npm i dotenv
    2. Create .env file and your variables inside
    3. Add the script to execute

      "dev": "nodemon -r dotenv/config ./app/index.js " or
      "start": "node -r dotenv/config ./app/index.js "
      
    4. Run the app using npm run dev or npm run start

    0 讨论(0)
  • 2020-12-09 02:54

    With recent versions of Node (since io.js 1.6), you can pass it the -r flag to require a module on start. This lets you directly load .env by using nodemon's --exec:

    nodemon --exec 'node -r dotenv/config'
    

    This requires the npm package dotenv to be installed.

    0 讨论(0)
  • 2020-12-09 02:58

    I have a production Procfile with:

    web: node web.js
    

    So I have created a Procfile_dev file with:

    web: nodemon web.js
    

    And when I am at development environment I run:

    $ foreman start -f Procfile_dev
    

    It works like a charm and doesn't affect production.

    0 讨论(0)
  • 2020-12-09 02:59

    You can get nodemon to directly use the .env with the following command

    $: env $(cat .env) nodemon app.js
    

    Be aware that you'll have to restart it if you make changes to .env and it won't like it if there are any spaces in your .env file.

    0 讨论(0)
  • 2020-12-09 03:00

    This works pretty well for me so far,

    nodemon  -w . -w .env index.js
    

    How it works:
    "-w ." tells nodemon to watch the files in the current directory
    "-w .env" tells nodemon to watch the .env file
    "index.js" is just the file to run when changes occur (could be anything)

    0 讨论(0)
提交回复
热议问题